Armstrong Number in Java

112
Check-armstrong-in-Java
Advertisement

In this blog, we will be discussing how to check whether a given number is an Armstrong number or not using Java.

An Armstrong number, also known as a narcissistic number, is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

To check if a number is an Armstrong number, we will use the following steps:

  1. Convert the given number to a string
  2. Find the length of the string
  3. Initialize a variable to store the sum of the digits raised to the power of the length of the string
  4. Iterate through the string, convert each character to an integer, and add it to the sum raised to the power of the length of the string
  5. Compare the sum with the original number
  6. If the sum is equal to the original number, the number is an Armstrong number. If not, it is not an Armstrong number.

Java Program

Here is the Java code for this process:

Java
public class ArmstrongNumber {
    public static void main(String[] args) {
        int num = 153;
        int originalNum = num;
        int sum = 0;
        int length = String.valueOf(num).length();
        while (num > 0) {
            int digit = num % 10;
            sum += Math.pow(digit, length);
            num /= 10;
        }
        if (sum == originalNum) {
            System.out.println(originalNum + " is an Armstrong number.");
        } else {
            System.out.println(originalNum + " is not an Armstrong number.");
        }
    }
}

In this code, we first define the variable num as 153, which is an Armstrong number. We then store the original value of num in a separate variable originalNum for later comparison. We initialize the sum variable to 0 and find the length of the number using the length() method of the String class.

We then use a while loop to iterate through the digits of the number. In each iteration, we find the last digit of the number using the modulus operator, raise it to the power of the length of the number, and add it to the sum variable. We then divide the number by 10 to get the next digit.

After the while loop, we compare the sum variable with the originalNum variable. If they are equal, the number is an Armstrong number and we print a message saying so. If not, we print a message saying the number is not an Armstrong number.

In this example, the output will be “153 is an Armstrong number.”

In conclusion, we have learned how to check whether a given number is an Armstrong number or not using Java. This process can be used to check for Armstrong numbers in a variety of applications and can be modified to work with larger numbers as well.

Latest Posts: