java

Armstrong Number in Java

A positive number is called an Armstrong number if it is equal to the sum of the cubes of its digits, for example, 0, 1, 153, 370, 371, 407, etc.

In other words, the following equation will be verified

xy..z = xn + yn + ….. + zn

n is the number of digits

For example, 370 is a 3-digit Armstrong number

370 = 33 + 73 + 03
        = 27 + 343 + 0
        = 370

Now we will see Armstrong’s implementation in Java.
 

 

Program to check if the given number is an Armstrong number
public class NbrArmstrong {

    public static void main(String[] args) {

        int n = 370;
        int nbr = n;
        int tmp; 
        int sum = 0;
      
        while (nbr != 0)
        {
            tmp = nbr % 10;
            sum = sum + tmp*tmp*tmp;
            nbr /= 10;
        }

        if(sum == n)
            System.out.println(n + " is an Armstrong number");
        else
            System.out.println(n + " is not an Armstrong number");
    }
}

Output:

370 is an Armstrong number
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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