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
9K
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

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.