Computer Science, asked by Anonymous, 11 months ago

write a program in Java to check whether the provided number is an Armstrong one or not​


Anonymous: Provide 30 points in total for this question.....And U will get a proper answer..
Anonymous: ok
Anonymous: BTW, how to do that?

Answers

Answered by QGP
5

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:

\sf 3^3 = 27 \\ 7^3 = 343 \\ 1^3 = 1 \\\\\\ \to 3^3+7^3+1^3 = 27+343+1 = 371 \\\\ \implies \boxed{3^3+7^3+1^3 = 371}

There are only six Armstrong numbers: 0, 1, 153, 370, 371 and 407.

 \rule{300}{1}

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

 \rule{300}{1}

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");

           

   }

}

Attachments:

Anonymous: thanks a lot!
QGP: You are welcome :)
Similar questions