Program to Find all Armstrong Numbers in a Range

A number n is said to be an Armstrong number if it is equal to the n-th power of its digits. For example consider the number 407,

The number of digits(n) is 3. The sum of 3rd power of the digits = 4^3+0^3+7^3 = 407. Hence 407 is an Armstrong number. All single digit numbers are Armstrong numbers while there are no 2 digit Armstrong numbers. Armstrong numbers are also known as Narcissistic numbers.

Finding all Armstrong Numbers in a Range Using Java

The following Java program finds all the Armstrong numbers in a given range. The program is coded to find Armstrong numbers between 0 and 99999.  You can easily change the range by modifying the values of starting_number and ending_number.

/* Java program to find Armstrong numbers in a range */

public class ArmstrongFinder {

    public static void main(String[] args) {
        int starting_number = 1;
        int ending_number = 99999;
        for (int i = starting_number; i <= ending_number; i++) {
            if (isArmstrong(i)) {
                System.out.println(i + " is an Armstrong number!");
            } else {
                
            }
        }
    }

    public static boolean isArmstrong(int n) {
        int no_of_digits = String.valueOf(n).length();
        int sum = 0;
        int value = n;
        for (int i = 1; i <= no_of_digits; i++) {
            int digit = value % 10;
            value = value / 10;
            sum = sum + (int) Math.pow(digit, no_of_digits);
        }
        if (sum == n) {
            return true;
        } else {
            return false;
        }
    }
}

The above program found the following Armstrong numbers between 0 and 99999,

1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply