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:
- Take the input number and store it in a variable.
- Find the number of digits in the input number.
- 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.
- 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.