Java Program to test if a given number is Armstrong Number or not

Java Program to test if a given number is Armstrong Number or not thumbnail
11K
By Dhiraj Ray 31 December, 2017

Description

Armstrong Number is a number that is the sum of its own digits each raised to the power of the number of digits.For example 371 is an Armstrong number as 3^3+7^3+1^3 = 371.It is also sometimes called as narcissistic number or pluperfect digital invariant (PPDI). Following is the java program to test if a given number is an armstrong number or not.

ArmstrongNumber.java
package com.devglan;

public class ArmstrongNumber {

    public boolean isArmstrongNumber(int number){

        int tmp = number;
        int noOfDigits = String.valueOf(number).length();
        int sum = 0;
        int div = 0;
        while(tmp > 0){
            Line 1 div = tmp % 10;
            int temp = 1;
            for(int i=0; i < noOfDigits; i++){
                temp *= div;
            }
            sum += temp;
            Line 7 tmp = tmp/10;
        }
        if(number == sum) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String a[]){
        ArmstrongNumber man = new ArmstrongNumber();
        System.out.println("Is 371 Armstrong number? " + man.isArmstrongNumber(371));
        System.out.println("Is 523 Armstrong number? " + man.isArmstrongNumber(523));
    }
}

Explanation

From line no. 1 to 7 - extract each digit and find it's nth square where n is the length of number and accumulate the sum of each result.Compare this result with the given number to identify if given nmber is an armstrong or not.

Share

❤️ Liked this article?

If it saved you time, consider buying me a coffee to support future improvements.

About The Author

author-image
I write about cryptography, web security, and secure software development. Creator of practical crypto validation tools at Devglan.