Algorithm


  1. Input:

    • Take an integer input (let's call it num) from the user.
  2. Initialization:

    • Initialize three variables: originalNum to store the original value of num, result to store the result of the Armstrong number check, and n to store the number of digits in num.
  3. Count Digits:

    • Calculate the number of digits in num and store it in n. You can use a loop to repeatedly divide num by 10 until it becomes zero, incrementing n in each iteration.
  4. Calculate Armstrong Number:

    • Initialize result to 0.
    • Iterate through each digit of originalNum using a loop.
      • Calculate the digit by taking the remainder when dividing originalNum by 10.
      • Update result by adding the digit raised to the power of n.
      • Divide originalNum by 10 to move to the next digit.
    • After the loop, check if result is equal to the original number num. If true, then num is an Armstrong number.
  5. Output:

    • Display the result, indicating whether the number is an Armstrong number or not.

 

Code Examples

#1 Code Example- Check Armstrong Number for 3 digit number

Code - Java Programming

public class Armstrong {

    public static void main(String[] args) {

        int number = 371, originalNumber, remainder, result = 0;

        originalNumber = number;

        while (originalNumber != 0)
        {
            remainder = originalNumber % 10;
            result += Math.pow(remainder, 3);
            originalNumber /= 10;
        }

        if(result == number)
            System.out.println(number + " is an Armstrong number.");
        else
            System.out.println(number + " is not an Armstrong number.");
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
371 is an Armstrong number.

#2 Code Example- Check Armstrong number for n digits

Code - Java Programming

public class Armstrong {

    public static void main(String[] args) {

        int number = 1634, originalNumber, remainder, result = 0, n = 0;

        originalNumber = number;

        for (;originalNumber != 0; originalNumber /= 10, ++n);

        originalNumber = number;

        for (;originalNumber != 0; originalNumber /= 10)
        {
            remainder = originalNumber % 10;
            result += Math.pow(remainder, n);
        }

        if(result == number)
            System.out.println(number + " is an Armstrong number.");
        else
            System.out.println(number + " is not an Armstrong number.");
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
1634 is an Armstrong number.
Advertisements

Demonstration


Java Programing Example to Check Armstrong Number-DevsEnv