Home page

Thursday, June 15, 2023

Armstrong number in JAVA

In simple terms, an Armstrong number is a number that is equal to the sum of its own digits, each raised to the power of the number of digits in it.

For example, let's consider the number 153. It has 3 digits. If we raise each digit to the power of 3 (the number of digits) and sum them up, we get:

1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

Since the sum of the digits raised to the power of the number of digits equals the original number (153), it is an Armstrong number.

Here's an example code in Java to check if a given number is an Armstrong number or not:

public class ArmstrongNumberExample {

    public static void main(String[] args) {

        int number = 153;

        boolean isArmstrong = isArmstrongNumber(number);

        if (isArmstrong) {

            System.out.println(number + " is an Armstrong number.");

        } else {

            System.out.println(number + " is not an Armstrong number.");

        }

    }

    public static boolean isArmstrongNumber(int number) {

        int originalNumber = number;

        int sum = 0;

        int digits = String.valueOf(number).length();

        while (number != 0) {

            int digit = number % 10;

            sum += Math.pow(digit, digits);

            number /= 10;

        }

        return sum == originalNumber;

    }

}

In this code, we have a method called isArmstrongNumber() that takes an integer as input and returns a boolean value indicating whether it is an Armstrong number or not.

Inside the method, we store the original number in a variable to compare later. We initialize a variable sum to keep track of the sum of the digits raised to the power of the number of digits. We calculate the number of digits in the given number using the String.valueOf(number).length().

We then use a while loop to extract each digit from the number. In each iteration, we find the last digit by taking the remainder of the number divided by 10. We raise this digit to the power of the number of digits and add it to the sum. Finally, we divide the number by 10 to remove the last digit.

After the loop ends, we compare the sum with the original number. If they are equal, the number is an Armstrong number and we return true. Otherwise, it is not an Armstrong number and we return false.

In the example, the number 153 is checked and found to be an Armstrong number, so the output will be:
153 is an Armstrong number.

No comments:

Post a Comment