Armstrong number
An Armstrong number is a number that is equal to the sum of the digits that rise to the total number of digits of the power. Some Armstrong numbers are: 0, 1, 2, 3, 153, 370, 407, 1634, 8208, etc.
Know more about Armstrong number – Wikipedia
Logic
After taking input from the user, we have to calculate the total number of digits in the given number. Here we are using log10 method of math library to achieve this. After doing that we have to run one loop until the value of user given number “num” does not reach 0 or becomes less than zero.
Now inside the loop each time we have to find the last digit of user given number and then calculate the power of that number with total no of digits in the “num”, round off the result and store it in one temporary variable “sum” once the loop is finished we have to check if the value of variable sum is equivalent to user given number, if yes, then it is an Armstrong number.
Program
import java.util.Scanner; public class CheckArmstrong { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int originalNum, num, lastDigit, digits; long sum = 0; System.out.print("Enter number to check : "); num = scanner.nextInt(); originalNum = num; // Find total digits in given number digits = (int) Math.log10(num) + 1; while(num > 0) { lastDigit = num % 10; sum = sum + Math.round(Math.pow(lastDigit, digits)); // Remove the last digit num = num / 10; } if(originalNum == sum) { System.out.println("\n" + originalNum + " is ARMSTRONG NUMBER"); } else { System.out.println("\n" + originalNum + " is NOT ARMSTRONG NUMBER"); } } }
Output
Enter number to check : 1634
1634 is ARMSTRONG NUMBER