Java Program to Check a Number is Armstrong

Java Program to Check Armstrong Number

In this example, we will  learn to check whether a given number is armstrong number or not.

A positive integer is called an Armstrong number of order n if

abcd... = an + bn + cn + dn + ...

In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the number itself.

For example:

153 = 1*1*1 + 5*5*5 + 3*3*3  // 153 is an Armstrong number.

Example 1:

public class Armstrong {

    public static void main(String[] args) {

        int number = 171, 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.");
    }
}

Output :

171 is not an Armstrong number

 

Example 2: Check Armstrong number for n digits

 

public class Armstrong {

    public static void main(String[] args) {

        int number = 153, myNumber, remainder, result = 0, n = 0;

        myNumber = number;

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

        myNumber = number;

        for (;myNumber != 0; myNumber /= 10)
        {
            remainder = myNumber % 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.");
    }
}

Output :

153 is an Armstrong number.


Subscribe For Daily Updates

JAVA File IO examples

JAVA Date & Time Progamming Examples

JAVA Collections

Flutter Questions
Android Questions