Java Program to Check Armstrong Number

In this article, we'll understand what an Armstrong number is and how to write a Java program to check for it. 

What is an Armstrong Number? 

An Armstrong number is an integer such that the sum of its own digits raised to the power of the number of digits is equal to the number itself. 

For instance, 153 is an Armstrong number because: 1^3 + 5^3 + 3^3 = 153 

The Strategy 

To determine if a number is an Armstrong number: 

  • Calculate the number of digits in the number (let's call it n). 
  • For each digit, raise it to the power n and accumulate the sum. 
  • If the accumulated sum equals the original number, it's an Armstrong number! 

The Java Program 

Time to pen down the program:

public class ArmstrongChecker {

    public static void main(String[] args) {
        int number = 153;
        if (isArmstrong(number)) {
            System.out.println(number + " is an Armstrong number!");
        } else {
            System.out.println(number + " is not an Armstrong number.");
        }
    }

    public static boolean isArmstrong(int num) {
        int original = num;
        int sum = 0;

        // Step 1: Find number of digits (n)
        int n = String.valueOf(num).length();

        // Step 2: For each digit, raise it to the power n and accumulate the sum
        while (num > 0) {
            int digit = num % 10;
            sum += Math.pow(digit, n);
            num /= 10;
        }

        // Step 3: Compare the sum with the original number
        return sum == original;
    }
}

Output:

153 is an Armstrong number!

Explaining the Program 

Find the Number of Digits:

int n = String.valueOf(num).length();

A quick trick to find the number of digits is by converting the number to a string and then finding its length. 

Calculate Sum of Digits Raised to the Power n:

while (num > 0) {
    int digit = num % 10;
    sum += Math.pow(digit, n);
    num /= 10;
}

We use a loop to extract each digit of the number using the modulo operation (%). Then, we use Math.pow to raise the digit to the power n and accumulate this in sum. The number is then reduced by dividing it by 10, and the loop continues until no more digits are left. 

Check if Sum Matches the Original Number:

return sum == original;

Finally, we check if our computed sum matches the original number. If it does, it's an Armstrong number.

Conclusion

You've just learned about Armstrong numbers and developed a Java program to detect them. This serves as a foundation for understanding number properties and using mathematical operations in programming. As you journey further into the world of coding, you'll come across more such intriguing number properties. Keep exploring and happy coding!

Comments