Armstrong number – java

How to check if a given number is an Armstrong number or not?

- Advertisement -

The sum of the power of individual digits is equal to the number itself is a Armstrong number.

Example1: 370

3*3*3 + 7*7*7 + 0*0*0 = 27 + 343 + 0 = 370

- Advertisement -

    public class ArmstrongNumber{
        public static void main(String[] args) {
            int num = 371, originalNum, remainder, result = 0;
            originalNum = num;
            while (originalNum != 0)
            {
                remainder = originalNum % 10;
                result += Math.pow(remainder, 3);
                originalNum /= 10;
            }   
            if(result == num)
                System.out.println(num + " is an Armstrong number.");
            else
                System.out.println(num + " is not an Armstrong number.");
        }
    }

 

 

Other logic:

public class Armstrong {
    public static void main(String[] args) {
        int number = 9474, 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.");
    }
}

 

 

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More