Check Armstrong Number using Java

Mathematics and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. Well, Armstrong numbers are very well known in the mathematical world. Therefore today we’re going to write a program to check if the given input number is Armstrong Number or not using Java.

 

What are Armstrong Numbers?

 

  • Let us consider Number X with N being the no digits in X. Then X will be said as the Armstrong number if the sum of each digit of X is raised with order N equals to X itself.

 

  • Eg:  153 is the Armstrong No.
  • Therefore, 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 = 153

 

Also Read: Check If Two Strings Are Anagram using Java

 

What’s The Approach?

 

  • Firstly in the input number (X), we will Find The Number Of Digits (N) so that we can determine the order.

 

  • Once we find the order, then for each digit (R) we will compute  RN

 

  • After that, we will perform the addition of the computed values.

 

  • If the addition equals N, then the number is Armstrong otherwise it’s Not.

 

Java Program To Check Armstrong Number

 

Input: x=153

    x=1523

 

Output: True

                 False

 

// Java program to determine whether the number is
// Armstrong number or not
public class Armstrong
{
    /* Function to calculate x raised to the
    power y */
    int power(int x, long y)
    {
        if( y == 0)
            return 1;
        if (y%2 == 0)
            return power(x, y/2)*power(x, y/2);
        return x*power(x, y/2)*power(x, y/2);
    }

    /* Function to calculate order of the number */
    int order(int x)
    {
        int n = 0;
        while (x != 0)
        {
            n++;
            x = x/10;
        }
        return n;
    }

    // Function to check whether the given number is
    // Armstrong number or not
    boolean isArmstrong (int x)
    {
        // Calling order function
        int n = order(x);
        int temp=x, sum=0;
        while (temp!=0)
        {
            int r = temp%10;
            sum = sum + power(r,n);
            temp = temp/10;
        }

        // If satisfies Armstrong condition
        return (sum == x);
    }

    // Driver Program
    public static void main(String[] args)
    {
        Armstrong ob = new Armstrong();
        int x = 153;
        System.out.println(ob.isArmstrong(x));
        x = 1253;
        System.out.println(ob.isArmstrong(x));
    }
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *