Find number is Armstrong or not

Armstrong number is a number which is equal to the sum of cubes of its digits. For example, 0, 1, 151, 370, 371, 407, etc. Let's try to understand why 371 is an Armstrong number.
371 = (3*3*3) + (7*7*7) + (1*1*1)
    =  27 + 343 + 1
    =  371

Here 371 = 371 , so it is an Armstrong number. To find ArmStrong number we have to first find out the remainder of number in loop and take the cube of it. After that add the result in 'res' varibale. And at last we compare the original number with 'res', if they are same then it is Armstrong number otherwiese no.

class ArmStrongNum {

 public static void main(String[] args) {

  int num = Integer.parseInt(args[0]);
  int n=num,res=0;

  while(n>0) {
   res = res + (int)Math.pow(n%10,3);
   n = n /10;
  if(num == res) {
   System.out.println(num+" == "+res);
   System.out.println("Hence the "+num+" is an armstrong no.");
  else {
   System.out.println(num+" != "+res);
   System.out.println("Hence the "+num+" is not an armstrong no.");
C:\>java ArmStrongNum 371
371 == 371
Hence the 371 is an armstrong no.
C:\>java ArmStrongNum 515
515 != 251
Hence the 515 is not an armstrong no.

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative