Program to Check Armstrong Number in Java
What is Armstrong number?
An n digit number is said to be an Armstrong number if the sum of n-th power of its digits is the n digit number itself. For example consider the number 371,
- The number of digits = 3
- The sum of 3rd power of digits = 3^3 + 7^3 + 1^3 = 27+343+1 = 371
Hence 371 is an Armstrong number. Some of the other Armstrong numbers are 6, 153 and 1634.
Checking for Armstrong Number in Java
The following program checks whether a given number is an Armstrong number.
/* Java program to check whether a given number is an Armstrong number */
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 an NOT Armstrong number!");
}
}
public static boolean isArmstrong(int n) {
int no_of_digits = String.valueOf(n).length();
int sum = 0;
int value = n;
for(int i=1;i<=no_of_digits;i++) {
int digit = value%10;
value = value/10;
sum = sum + (int)Math.pow(digit, no_of_digits);
}
if(sum == n) {
return true;
}else {
return false;
}
}
}