Click here to Skip to main content
15,884,739 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
class ArmstrongNumber
{
   public static void main(String args[])
   {
      int n, sum = 0, temp, r;

      Scanner in = new Scanner(System.in);
      System.out.println("Enter a number to check if it is an armstrong number");
      n = in.nextInt();

      temp = n;

      while( temp != 0 )
      {
         r = temp%10;
         sum = sum + r*r*r;
  temp = temp/10;
      }

      if ( n == sum )

         System.out.println("Entered number is an armstrong number.");
      else
         System.out.println("Entered number is not an armstrong number.");
   }
}
Posted
Comments
Sergey Alexandrovich Kryukov 4-Aug-14 11:21am    
There is nothing to understand. It just checking up if n is equal to sum and displays appropriate message. The code you show is bad, why studying it? Better write your own code which would check up if the number is Armstrong number or not. This is way too easy problem; perhaps you can write a correct solution. :-)
—SA
PIEBALDconsult 4-Aug-14 11:29am    
By "after the 'while' loop" do you mean the if statement? Or do you mean the contents of the while loop?


Personally, I would iterate the digits in the string rather than use the loop you have.
I also see opportunities to short-circuit the process.

I'll also point out that that code will only work for three-digit base-10 values.
Sergey Alexandrovich Kryukov 4-Aug-14 11:55am    
Which actually means that it does not work at all... :-)
—SA
PIEBALDconsult 4-Aug-14 11:57am    
I considered adding an "at most" qualifier.
Sergey Alexandrovich Kryukov 4-Aug-14 12:33pm    
:-)

It is simple: as required it sums the cubes of the digits of the given number and, at the end, compares such sum with the given number itself.

Before the while starts, temp is equal to n (the given number).
At first iteration, r is equal to the least significant digit of temp (e.g if number is 123, than r=3). Then the cube of r is added to sum. Finally temp is divided by 10, discarding the remainder (because it uses the integer division, e.g. temp=123 becomes temp=12). The process is repeated at next iterations, until temp becomes 0, that is all the digits have been used.

You might easily check it with a debugger.
 
Share this answer
 
Here is a good advice for you: stop looking at all kind of trash; instead, take the definition of the Armstrong number and solve this really simple problem by yourself: http://en.wikipedia.org/wiki/Armstrong_number[^].

Even if you, by some reason, fail to solve it, you will be able to ask a reasonable question at this forum.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900