Find If a Number is Armstrong Number - Java Program
Armstrong Number is a number in which sum of the n-th power of its digits equals the number. n is the number of digits. For example, 153, 370 and 371 are armstrong numbers
- For 3 digit numbers, Number is an Armstrong Number if sum of the cubes of the digits equals the number itself.
- For 4 digit numbers, Number is an Armstrong Number if sum of the 4th power of the digits equals the number itself.
- For single digit numbers, Number is always an Armstrong Number.
- For 2 digit numbers, Number is an Armstrong Number if sum of the square of the digits equals the number itself. However, there is no 2-digit armstrong number.
Armstrong Number Examples
01 = 0 11 = 1 21 = 2 Similarly: 3,4,5,6,7,8,9 are Armstrong Numbers 153 = 13 + 53 + 33 = 1 + 125 + 27 = 153 370 = 33 + 73 + 23 = 27 + 343 + 0 = 370 371 = 33 + 73 + 13 = 27 + 343 + 1 = 371 407 = 43 + 03 + 73 = 64 + 0 + 343 = 407 1634 = 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1634 8208 = 84 + 24 + 04 + 84 = 4096 + 16 + 0 + 4096 = 8208 9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474
Armstrong Number - Java Program
import java.util.Scanner;
public class ArmstrongNumber {
public static void main (String args[]) {
System.out.println("Enter the Number:");
Scanner scanner= new Scanner(System.in);
String sNum =scanner.nextLine();
int num = Integer.parseInt(sNum);
System.out.println("num:" + num);
scanner.close();
int sum = 0;
int temp= num;
while(temp>0) {
int digit = temp % 10;
sum=sum + (digit*digit*digit);
System.out.println(
"digit:" + digit
+ ",sum:" + sum + " ");
temp = temp - digit;
temp = temp / 10;
}
if(sum==num) {
System.out.println("" + num
+ " is an Armstrong Number");
}
else {
System.out.println("" + num
+ " is not an Armstrong Number");
}
}
}
If the input is 153, Output will be:
153 is an Armstrong Number
If the input is 200, Output will be:
200 is not an Armstrong Number