write a program in Java to check whether the provided number is an Armstrong one or not
Answers
Armstrong Number - Java
Armstrong Numbers are those for which the sum of cubes of the digits is same as the original number.
For example, 371 is an Armstrong Number:
There are only six Armstrong numbers: 0, 1, 153, 370, 371 and 407.
We need to write a Java program to check if a given number is an Armstrong Number or not.
Our general algorithm would be something like this:
- Take User input of number through Scanner
- Store its value in another variable for later comparison
- Initialise a sum variable to 0
- Run a loop to extract digits of the number
- In each iteration of the loop, add the cube of the digit to sum
- Finally, Compare the sum with the original value we stored earlier
- If both sum and original number are same, then the number is an Armstrong Number
import java.util.Scanner;
public class ArmstrongNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("A number is an Armstrong number, if the sum of cubes of the digits is equal to the original number.");
System.out.print("Enter a number: ");
long number = sc.nextLong(); //Taking User Input
long originalValue = number; //Using another variable with same number to store original value
long sum=0; //Initialising sum to 0
do
{
long digit = number % 10; //Extracting digit
sum += digit * digit * digit; //Adding the cube of the digit to sum
number /= 10; //Dividing by 10 for next digit in next loop iteration
}
while(number!=0);
if (sum==originalValue) //Comparing Sum of Cube of digits to original number
System.out.println(originalValue+" is an Armstrong number");
else
System.out.println(originalValue+" is not an Armstrong number");
}
}