Study Guides/Computer Science/Armstrong Number in Java and Python
Study Guide · Computer Science

Armstrong Number – Program in Java and Python

An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits each raised to the power of the number of digits.

Example: 153 = 1³ + 5³ + 3³ = 1 + 125 + 27 = 153

Question (Click to Flip)

What is an Armstrong number?

Answer

An Armstrong number equals the sum of its own digits, each raised to the power equal to the number of digits. Example: 153 = 1³ + 5³ + 3³.

Card 1 of 2 free previews

Key Facts

Definition: Sum of (each digit)^(number of digits) equals the number itself.

3-digit Examples: 153, 370, 371, 407.

Also Called: Narcissistic numbers or Pluperfect digital invariants.

Logic: Extract each digit, raise to power n, sum them up.

More Examples

  • 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 — all single digit numbers are Armstrong.
  • 153 (3 digits): 1³+5³+3³ = 153 ✓
  • 370 (3 digits): 3³+7³+0³ = 27+343+0 = 370 ✓
  • 371 (3 digits): 3³+7³+1³ = 371 ✓
  • 407: 4³+0³+7³ = 64+0+343 = 407 ✓

Python Program

num = int(input('Enter a number: '))
original = num
result = 0
n = len(str(num))  # number of digits
while num > 0:
    digit = num % 10
    result += digit ** n
    num //= 10
if result == original:
    print(f'{original} is an Armstrong number')
else:
    print(f'{original} is NOT an Armstrong number')

Java Program

import java.util.Scanner;
public class Armstrong {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int original = num, result = 0;
        int n = String.valueOf(num).length();
        while (num > 0) {
            int digit = num % 10;
            result += Math.pow(digit, n);
            num /= 10;
        }
        if (result == original)
            System.out.println(original + " is Armstrong");
        else
            System.out.println(original + " is not Armstrong");
    }
}

Questions and Answers

What is an Armstrong number?+

An Armstrong number equals the sum of its own digits, each raised to the power equal to the number of digits. Example: 153 = 1³ + 5³ + 3³.

Is 9474 an Armstrong number?+

Yes! 9474 is a 4-digit Armstrong number: 9⁴ + 4⁴ + 7⁴ + 4⁴ = 6561+256+2401+256 = 9474.

More in Computer Science

Study Smarter with Shinyu.ai

Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast — free, no signup required.