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.
Example to show Armstrong number determination
Input number to check – 370
Applying the above given 4 steps –
- 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.
Java code to determine whether given number is Armstrong or not
OUTPUT for different input values Explanation of the code
Scannerinstance to fetch the given number entered by the user to be checked for an Armstrong number.
- The input number is converted from a
Stringvalue to a
inputNois sent as a parameter to the method
countNoOfDigits()which returns the total number of digits in
inputNoand stores it in the variable
countNoOfDigits()works by dividing the
10in 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.
digitCountare sent as parameters to
calculateSum()method separates the digits of
inputNoby 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 the
inputNoto determine whether the given number is an Armstrong number or not.
In this tutorial we looked at what is an Armstrong number and then saw Java code for implementing Armstrong number check along with detailed explanation of the code.