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.

  1. Start.
  2. Read/Take number into number_lhs. We have to check if this number is Armstrong or not.
  3. Initialize number_length with number of digits in number_lhs.
  4. Initialize number_rhs with 0.
  5. Initialize temporary variables i with 0 and number with number_lhs.
  6. Check if i is less than number_length. If false go to step 9.
  7. Get the last digit of the number using modulus operator. Compute power of this digit raised to number_length. Add this to number_rhs.
  8. Increment i and update number with its last digit removed using Arithmetic Division operator. Go to step 6.
  9. If number_lhs is equal to number_rhs, given number is Armstrong number. Otherwise not.
  10. 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.