Follow @devglan
Java Program to test if a given number is Armstrong Number or not
Description
Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits.For example 371 is an Armstrong number as 3^3+7^3+1^3 = 371.It is also sometimes called as narcissistic number or pluperfect digital invariant (PPDI). Following is the java program to test if a given number is an armstrong number or not.
ArmstrongNumber.javapackage com.devglan; public class ArmstrongNumber { public boolean isArmstrongNumber(int number){ int tmp = number; int noOfDigits = String.valueOf(number).length(); int sum = 0; int div = 0; while(tmp > 0){ Line 1 div = tmp % 10; int temp = 1; for(int i=0; i < noOfDigits; i++){ temp *= div; } sum += temp; Line 7 tmp = tmp/10; } if(number == sum) { return true; } else { return false; } } public static void main(String a[]){ ArmstrongNumber man = new ArmstrongNumber(); System.out.println("Is 371 Armstrong number? " + man.isArmstrongNumber(371)); System.out.println("Is 523 Armstrong number? " + man.isArmstrongNumber(523)); } }
Explanation
Click to Suggest Your Own Explanation
From line no. 1 to 7 - extract each digit and find it's nth square where n is the length of number and accumulate the sum of each result.Compare this result with the given number to identify if given nmber is an armstrong or not.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.