Java Armstrong Number Program

An Armstrong number (narcissistic number) is a number which is equal to the sum of its digits, each raised to the power of the number of digits. For example 153 = 1^3 + 5^3 + 3^3.

Program

public class Main {
    static boolean isArmstrong(int number) {
        int digits = String.valueOf(number).length();
        int sum = 0;
        int n = number;
        while (n > 0) {
            int digit = n % 10;
            sum += (int) Math.pow(digit, digits);
            n /= 10;
        }
        return sum == number;
    }

    public static void main(String[] args) {
        System.out.println(isArmstrong(153));
        System.out.println(isArmstrong(154));
        System.out.println(isArmstrong(9474));

        System.out.print("Armstrong numbers up to 1000: ");
        for (int i = 1; i <= 1000; i++) {
            if (isArmstrong(i)) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}
Output

true
false
true
Armstrong numbers up to 1000: 1 2 3 4 5 6 7 8 9 153 370 371 407

How it works

  • String.valueOf(number).length() counts the digits.
  • The loop takes the last digit with % 10, raises it to the power of the digit count, and adds it.
  • Every single digit number (1 to 9) is an Armstrong number, because d^1 = d.

Related: Java while Loop and Java Math Class.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.