Sunday 3 May 2015

Java Program to find Armstrong numbers

 Java Program to find Armstrong numbers


An Armstrong number is a three digit number for which sum of cube of its digit is equal to the number. Example of Armstrong number is 153 as

                   153= 1+ 125+27 which 1^3+5^3+3^3.

 Another Armstrong number is 371.


import java.util.Scanner;

public class ArmstrongTest {

    public static void main(String[] args) {

        System.out.println("Enetr Number");
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        System.out.println("Given Number =" + num + " is Armstrong="
                + isArmstrong(num));
    }

    private static boolean isArmstrong(int num) {
        int dummy = 0;
        int rem = 0;
        int originalNum = num;
        while (num > 0) {
            rem = num % 10;
            num /= 10;
            dummy += rem * rem * rem;
        }
        return (originalNum == dummy);
    }

}

OutPut:

Enetr Number
153
Given Number =153 is Armstrong=true

+++++++++++++++++++++++++

Enetr Number
200
Given Number =200 is Armstrong=false

+++++++++++++++++++++++++


Enetr Number
371
Given Number =371 is Armstrong=true

No comments:

Post a Comment