Armstrong Number in Java
Last updated: February 8, 2025
An Armstrong Number (also known as a Narcissistic Number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. In this blog, we will understand the concept and learn how to check Armstrong numbers using Java.
What is an Armstrong Number?
A number with n digits is an Armstrong number if:
sum = digit₁ⁿ + digit₂ⁿ + digit₃ⁿ + ... + digitₙⁿ
If the sum equals the original number, it is an Armstrong number.
Examples
- 153 → 1³ + 5³ + 3³ = 153
- 370 → 3³ + 7³ + 0³ = 370
- 9474 → 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474
Java Program to Check Armstrong Number
Below is a simple Java program using loops and math logic:
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int original = num;
int sum = 0;
// count digits
int digits = String.valueOf(num).length();
while (num > 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}
if (sum == original) {
System.out.println(original + " is an Armstrong Number.");
} else {
System.out.println(original + " is NOT an Armstrong Number.");
}
}
}
Optimized Version
A slightly optimized solution that avoids converting the number to string:
public static boolean isArmstrong(int num) {
int digits = 0, temp = num;
// count digits
while (temp > 0) {
temp /= 10;
digits++;
}
int sum = 0;
temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
}
return sum == num;
}
Conclusion
Armstrong numbers are a classic programming exercise useful for practicing loops, conditionals, and mathematical logic in Java. Try modifying the program to find Armstrong numbers in a range or generate all Armstrong numbers up to 10000.