Java Program to check a given number is armstrong or not.
Objective
Write a Java program to check whether a given integer is an Armstrong number.
Algorithm / Approach
- Read an integer
xand store it intemp. - First, count the number of digits in
xand store it indigits. - Reset
tempback tox. - Start a loop to extract digits. For each digit, calculate
digitdigitsusingMath.pow(). - Add the powered result to a
sumaccumulator. - If the final
sumequals the original numberx, it is an Armstrong number.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
int x,rem,p=0,sum=0, digits =0;
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
x = s.nextInt();
int temp = x;
while(temp>0) {
temp /= 10;
digits++;
}
temp = x;
while(temp!=0) {
rem = temp%10;
p =(int) Math.pow(rem,digits);
sum = sum+p;
temp = temp/10;
}
if(sum==x) {
System.out.print("Armstrong Num.");
}
else {
System.out.print("Not Armstrong Num.");
}
}
}
Expected Output
Enter a Num: 153 Armstrong Num.
Explanation of the Program
- An Armstrong number (or Narcissistic number) for a given number of digits is an integer such that the sum of its digits each raised to the power of the total number of digits equals the number itself.
- For example, 153 has 3 digits. 13 + 53 + 33 = 1 + 125 + 27 = 153.
- The program requires two distinct loops: the first pass simply counts the digits, and the second pass performs the digit extraction and exponentiation.
Complexity
Time Complexity
O(log10(x)) - Counting digits and processing them both take time proportional to the number of digits.
Space Complexity
O(1)
Common Mistakes
- Assuming the power is always 3 (which is only true for 3-digit Armstrong numbers). True Armstrong number logic requires calculating the dynamic digit length first.
- Not casting the result of
Math.pow()to anint.