Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to check a given number is armstrong or not.

Java Code Example — Simple Programs

ADVERTISEMENT

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

  1. Read an integer x and store it in temp.
  2. First, count the number of digits in x and store it in digits.
  3. Reset temp back to x.
  4. Start a loop to extract digits. For each digit, calculate digitdigits using Math.pow().
  5. Add the powered result to a sum accumulator.
  6. If the final sum equals the original number x, 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 an int.
ADVERTISEMENT