what is armstrong number in java

what is armstrong number in java

1 year ago 30
Nature

An Armstrong number is a number that is equal to the sum of its digits raised to the power of the total number of digits in the number. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153. In Java, we can check whether a given number is an Armstrong number or not using the following algorithm:

  1. Take the input number and store it in a variable.
  2. Find the number of digits in the input number.
  3. Loop through the digits of the input number and calculate the sum of each digit raised to the power of the total number of digits.
  4. Compare the sum with the input number. If they are equal, the input number is an Armstrong number.

Here is an example Java program to check whether a given number is an Armstrong number or not:

import java.util.Scanner;

public class ArmstrongNumber {
    public static void main(String[] args) {
        int num, number, temp, total = 0;
        System.out.println("Enter a number:");
        Scanner scanner = new Scanner(System.in);
        num = scanner.nextInt();
        scanner.close();
        number = num;
        int digits = String.valueOf(num).length();
        while (number != 0) {
            temp = number % 10;
            total += Math.pow(temp, digits);
            number /= 10;
        }
        if (total == num)
            System.out.println(num + " is an Armstrong number");
        else
            System.out.println(num + " is not an Armstrong number");
    }
}

In this program, we take the input number from the user and find the number of digits in the input number using the String.valueOf(num).length() method. We then loop through the digits of the input number and calculate the sum of each digit raised to the power of the total number of digits using the Math.pow() method. Finally, we compare the sum with the input number and print whether it is an Armstrong number or not.

Read Entire Article