Java Program to Check Armstrong Number
To check if a number is an Armstrong Number, use a looping statement to compute the formula of Armstrong Number given below, and check if LHS is equal to RHS.
In this tutorial, we shall use for loop to compute the formula of an Armstrong Number.
A number is an Armstrong Number, if it obeys the following condition.
abcd...m = a^n + b^n + c^n + d^n + ... + m^n
where n
is the number of digits in given number abcd...m
and a, b, c, d, ..., m
are the digits in the number.
Algorithm
Following algorithm lets you find out if given number is an Armstrong Number or not.
- Start.
- Read/Take number into
number_lhs
. We have to check if this number is Armstrong or not. - Initialize
number_length
with number of digits innumber_lhs
. - Initialize
number_rhs
with0
. - Initialize temporary variables
i
with0
andnumber
withnumber_lhs
. - Check if
i
is less thannumber_length
. If false go to step 9. - Get the last digit of the
number
using modulus operator. Compute power of this digit raised tonumber_length
. Add this tonumber_rhs
. - Increment
i
and updatenumber
with its last digit removed using Arithmetic Division operator. Go to step 6. - If
number_lhs
is equal tonumber_rhs
, given number is Armstrong number. Otherwise not. - Stop.
Armstrong Number Program
Java Program
</>
Copy
/**
* Java Example Program to get Array Length
*/
public class ArmstrongNumber {
public static void main(String[] args) {
//check if this is Armstrong Number
int number_lhs = 153;
int number_length = (number_lhs+"").length();
int number_rhs = 0;
for (int i = 0, number = number_lhs; i < number_length; i++, number /= 10) {
number_rhs += Math.pow(number%10, number_length);
}
if (number_lhs == number_rhs)
System.out.println(number_lhs + " is an Armstrong Number.");
else
System.out.println(number_lhs + " is not an Armstrong Number.");
}
}
Output
153 is an Armstrong Number.
Conclusion
In this Java Tutorial, we learned how to check if a given number is Armstrong Number or not.