Java program for Armstrong Number

Category: Java program coding interview questions on numbers

Given number is z , determine whether this number is Armstrong Number or not. A positive integer number of n digits is called an Armstrong Number of order n if

abcd…=pow(a,n) + pow(b, n) +pow(c,n)+pow(d,n)+………, where a, b, c, d are digits of input number abcd….., n is the number of digits present in the number.

Approach

  1. First count the number of digits present in the given number z. Let the number of digits be n.
  2. For every digits present in the number z ,let digits are d1 , d2 , d3,…..;compute d1^n , d2^n , d3^n……..
  3. If the sum of all computed digits are equal to z i.e. d1^n+d2^n+d3^n+……..=z; it is an armstrong number, then print that this number is an armstrong number, else print this number is not an armstrong number.

Example:

153 is an armstrong number because

1^3+5^3+3^3=153

1634 is a 4 digit armstrong number because

1^4+6^4+3^4+4^4=1634

Java Program to check a number is Armstrong Number Or Not

public class ArmstrongNumber {

public static void main (String args[]) {

// code to enter a number you want to check armstrong number or not

Scanner sc = new Scanner(System.in);

System.out.println(“Enter the number you want to check whether armstrong number or not”);

int n = sc.nextInt();

int temp=n,digits=0,rev,sum=0;

//To find the number of digits:

while(temp>0) {

temp=temp/10;

digits++;

}

temp=n;

while (temp > 0) {

//To find the last digit

rem=temp%10;

//Sum up of the each digit to the power total number of digits present in the number

sum + = Math.pow(rem,digits);

//To remove the last digit

temp=temp/10;

}

if (sum==n) {

System.out.println(“The given number is an armstrong number”);

}

else

System.out.println(“The given number is not an armstrong number”);

}

}

}

If you don’t understand how to find the number of digits java program and how to sum up each digits of a number,

Check the following :

Java Program to count the number of digits in a given number

Leave a Reply

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