An Armstrong number (also called a Narcissistic number) is a number in which the sum of each digit raised to the power of the total number of digits is equal to the original number.
Simple Definition
A number is an Armstrong number if
Sum of (each digit ^ number of digits) = original number
Examples of Armstrong Numbers
✔ 3-Digit Armstrong Number
153
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
✔ More Examples
370 → 3³ + 7³ + 0³ = 370
371 → 3³ + 7³ + 1³ = 371
9474 → 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474
Logic to Check Armstrong Number in Java
To check whether a number is Armstrong or not, follow these steps:
Input the number
Count the number of digits
Extract each digit using
%operatorRaise each digit to the power of total digits
Add the result
Compare sum with original number
Java Program to Check Armstrong Number
import java.util.Scanner;
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;
int digits = 0;
int temp = num;
// Step 1: Count digits
while (temp != 0) {
digits++;
temp /= 10;
}
temp = num;
// Step 2: Calculate Armstrong sum
while (temp != 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
}
// Step 3: Compare
if (sum == original) {
System.out.println(original + " is an Armstrong number");
} else {
System.out.println(original + " is not an Armstrong number");
}
}
}
Dry Run of Program (Example: 153)
| Step | Value |
|---|---|
| Input number | 153 |
| Number of digits | 3 |
| Digits extracted | 3, 5, 1 |
| Calculation | 3³ + 5³ + 1³ |
| Sum | 27 + 125 + 1 = 153 |
| Output | Armstrong Number |
Armstrong Number for 4-Digit Numbers
This logic also works for 4-digit, 5-digit, or any length numbers.
Example:
9474 → 9⁴ + 4⁴ + 7⁴ + 4⁴ = 9474 ✔
Why Armstrong Numbers Are Important?
Frequently asked in BCA / MCA / ICSE / CBSE exams
Helps understand loops, conditions, math logic
Improves problem-solving skills in Java
Common interview and coding test question
Time and Space Complexity
Time Complexity: O(n)
Space Complexity: O(1)
(where n = number of digits)
Key Points to Remember
✔ Uses modulus (%) to extract digits
✔ Uses Math.pow() for power calculation
✔ Works for any number of digits
✔ Logic-based and exam-friendly program
Comments
Post a Comment