Armstrong Number in Java - What is an Armstrong number

 

Armstrong Number in Java

Armstrong Number in Java

A number is said to be an Armstrong number when the summation of each digit cube of a number is equal to the original number.

Example 0, 1, 153, 370, 371, 407 etc.

Let’s check 153 is an Armstrong number or not.

153 = (1 * 1 * 1) + (5 * 5 * 5) + (3 * 3 * 3) 

153 = 1 + 125 + 27 is equal to 153.

Check another number 407 is an Armstrong number or not.

407 = (4 * 4 * 4) + (0 * 0 * 0) + (7 * 7 * 7)

407 =  64 + 0 + 343 is equal to 407 so it is an Armstrong

 

Java program to check Armstrong's number.

public class ArmstronNumber

{

    public static void main(String args[])

    {

        int num;       // Number to Check Armstrong no.

        int temp;      // temp variable to store the number

        int digit;  // last digit taker

        int arm=0;     // variable to store the cube of a digit

        num = 153;     // number to be checked

        temp = num;    // store the number

        while(num != 0)

        {

            digit = num % 10;

            arm  = arm + digit * digit * digit;

            num = num / 10;

        }

        if(temp == arm)

            System.out.println("Armstrong Number");

        else

            System.out.println("Not Armstrong number");

    }

}

In the above program, we have taken 153 as an example for checking the Armstrong number. We have taken each digit cube and summed it up to variable arm then check it, if it is equal to 153 then it is an Armstrong number.

 Java Program to Check Armstrong Number with method

import java.util.*;

public class ArmstronNumWithMethod

{

    int num;       // Number to Check Armstrong no.

    int digit;       // last digit taker

    int arm=0;   // variable to store the cube of a digit   

    // method

    int armstronNumber(int n)

    {

        num = n;

        while(num != 0)

        {

            digit = num % 10;

            arm  = arm + digit * digit * digit;

            num = num / 10;

        }

        return arm;

    }

    // main method started

    public static void main(String args[])

    {

        int number, armNum;

        Scanner sc = new Scanner(System.in);

        // object of the class

        ArmstronNumWithMethod ob = new ArmstronNumWithMethod();

        System.out.println("Enter a number :");

        number = sc.nextInt();

        // call the method with number as parameter       

        armNum = ob.armstronNumber(number);

        if(number == armNum)

            System.out.println(number + " is Armstrong Number");

        else

            System.out.println(number + " is not Armstrong number");

    } // main method end

} // end of class

More Java program



SHARE THIS
Previous Post
Next Post