Java program to check for an Armstrong Number
This tutorial provides the java implementation for Armstrong Number determination. It first explains what exactly is an Armstrong number, then provides the java code to check whether a given number is an Armstrong number or not, and finally provides a detailed step-by-step explanation of the java code.
What is Armstrong Number
Any number which equals the sum of each of its digits raised to the power of the total number of digits is an Armstrong number.
Other names for Armstrong number - Narcissistic number, pluperfect digital invariant, plus perfect number.
To check a given number for an Armstrong number the following steps need to be followed -
- Count the total number of digits in the given number. Lets say it is 'n'.
- Separate the digits of the number. Lets say the number is - 'd1 d2...dn' where dk is the digit at position 'k'.
- Calculate the sum of each of the digits raised to the total count of digits. This will be - (d1)n+(d2)n...+(dn)n.
- If the given number equals the sum obtained in step-3, then its an Armstrong number, else not.
- Number of digits in 370 - 3.
- Separate the digits in 370 - 3,7,0.
- Calculate the sum -(3)3+(7)3+(0)3 = 370.
- Sum obtained in step-3 is 370 which is equal to the given number. Hence, 370 is an Armstrong number.
ArmstrongNumberCheck
uses aScanner
instance to fetch the given number entered by the user to be checked for an Armstrong number.- The input number is converted from a
String
value to along
value, namedinputNo
, usingLong.parseLong()
method. inputNo
is sent as a parameter to the methodcountNoOfDigits()
which returns the total number of digits ininputNo
and stores it in the variabledigitCount
.countNoOfDigits()
works by dividing theinputNo
by10
in a loop. For every iteration the rightmost digit is removed (as remainders are not retained in a long value). So, for n iterations, n rightmost digits are removed, and once the number is 0, there is no digit remaining. At this point n will be the count of number of digits in the number.inputNo
anddigitCount
are sent as parameters tocalculateSum()
method.calculateSum()
method separates the digits ofinputNo
by using %(remainder) by 10. In each loop, the remainder on dividing by 10 is the rightmost digit of the number.Math.pow()
method is used to calculate the sum of digits raised to the total count of digits.- The sum obtained is returned to the
main()
method. This sum value is compared to theinputNo
to determine whether the given number is an Armstrong number or not.