Program to Check Armstrong Number
In this article we are going to understand what Armstrong number is and how we can check whether a number is Armstrong number or not in Java with examples.
Armstrong numbers are numbers which are equal to the sum of all its digits raised to the power equal to number of digits in the number.
Example :
5: 51=5 Armstrong number
10: 12+02 = 1 Not an Armstrong number
153= 13+53+33=153 Armstrong number
In the above examples the numbers 5 and 153 are Armstrong numbers as their digits when raised to the power of number of digits is equal to the number itself. However 10 is not the Armstrong number here.
Let’s see different ways to check Armstrong number.
Approach :
- We ask the user to enter a number or declare a number and store it .
- We calculate the number of digits in the number and store it in a variable digits.
- The number is raised to the power stored in variable digits. Then all of them are added.
- If the sum is equal to the entered number, then the number is said to be a Armstrong number.
Method-1: By Using Static Value
import java.util.Scanner; public class ArmstrongNumber { public static void main(String args[]) { //A number declared int num = 153; int sum = 0, temp = num, remainder; //numberOfDig() method called to get total number of digits in the actual number int digits = numberOfDig(num); //Iterates through the digits and adds the their raised power to sum while(temp>0) { remainder = temp%10; sum = sum + (int)Math.pow(remainder,digits); temp = temp/10; } if(sum==num) { System.out.println(num+" is an Armstrong Number"); } else { System.out.println(num+" is Not an Armstrong Number"); } } //method that returns the number of digits static int numberOfDig(int num) { int digits = 0; while (num > 0) { digits++; num = num / 10; } return digits; } }
Output: 153 is an Armstrong Number
Method-2: By User Input Value
import java.util.Scanner; public class ArmstrongNumber { public static void main(String args[]) { //Taking the number as input from the user using scanner class Scanner scan = new Scanner(System.in); System.out.print("Enter a number : "); int num = scan.nextInt(); int sum = 0, temp = num, remainder; //numberOfDig() method called to get total number of digits in the actual number int digits = numberOfDig(num); //Iterates through the digits and adds the their raised power to sum while(temp>0) { remainder = temp%10; sum = sum + (int)Math.pow(remainder,digits); temp = temp/10; } if(sum==num) { System.out.println(num+" is an Armstrong Number"); } else { System.out.println(num+" is Not an Armstrong Number"); } } //method that returns the number of digits static int numberOfDig(int num) { int digits = 0; while (num > 0) { digits++; num = num / 10; } return digits; } }
Output: Case-1 Enter a number : 153 153 is an Armstrong Number Case-2 Enter a number : 3567 3567 is an Armstrong Number