Armstrong Number in Java

Armstrong Number is a positive integer that is equal to the sum of its own digits raised to the power of number of digits. For example 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084 etc. Here we are going to write programs for Armstrong number in Java.

Steps to check Armstrong Number

To check if a number is an Armstrong Number, we can follow the following Steps –

  • Split the number and extract individual digits.
  • Calculate the power of each digit to the number of digits.
  • Calculate the sum of the power of each digit.
  • If calculate sum is equal to the original number, then the number is an Armstrong number.

Java Program to check Armstrong Number

Let’s write Java program to check if a given number is an Armstrong number or not

import java.util.Scanner;
public class ArmstrongNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Number");
        int number = sc.nextInt();
        int originalNumber = number;
        int sum=0, numberOfDigit=0;

//      calculate the number of digits in number
        while(number>0){
            numberOfDigit++;
            number/=10;
        }

        number = originalNumber;

//      Calculate the sum of the power of each digit to the number of digits.
        while(number>0){
            int digit = number%10;
            sum += Math.pow(digit,numberOfDigit);
            number/=10;
        }

        if(sum==originalNumber)
            System.out.println(originalNumber+ " is an Armstrong Number");
        else
            System.out.println(originalNumber+ " is not an Armstrong Number");

    }
}

Output

Armstrong Number in Java

Java Program to print Armstrong Number in range 1 to n

import java.util.Scanner;
public class ArmstrongNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the n");
        int n = sc.nextInt();

        for (int i = 1; i <= n; i++) {

            int originalNumber = i;
            int sum = 0, numberOfDigit = 0;

//      calculate the number of digits in number
            while (i > 0) {

                numberOfDigit++;
                i /= 10;
            }
            i = originalNumber;

//      Calculate the sum of the power of each digit to the number of digits.
            while (i > 0) {
                int digit = i % 10;
                sum += Math.pow(digit, numberOfDigit);
                i /= 10;
            }

            if (sum == originalNumber)
                System.out.print(originalNumber+", ");
            i =originalNumber;
        }
    }
}

Output

Armstrong number in java

See Also

1 thought on “Armstrong Number in Java”

Leave a Comment