Java: Armstrong Numbers up to a Limit

What is an Armstrong number…? How do we get these numbers…?
If sum of cube of individual numbers of a number is same to that number, then we can say that, that is an Armstrong number.



Examples: 1,153, 370, 371, 407…..


1 = 13
153 = 1+ 53 + 33
370 = 33 + 73 + 03
371 = 33 + 73 + 13
407 = 43 + 03 + 73


This is a Java console program to print or display Armstrong numbers up to a limit:


import java.io.*;
class armstrongno
{
  int limit,bal,i;
 double sum;
  int num,temp;
void display() throws IOException
 {
  BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("\n Enter the limit : ");
   limit = Integer.parseInt(Br.readLine());
   System.out.println("\n Armstrong numbers below " + limit + " : " );
  for(i = 1; i<limit;i++)
   {
     num = i;
temp = i;
sum = 0;
       while(num>0)
               {
   bal = num % 10;
           num = num / 10;
           sum = sum + Math.pow(bal,3);
          }
if(temp==sum)
  {
  System.out.println(sum);
  }
}
  }
 public static void main(String s[]) throws IOException
  {
   armstrongno an = new armstrongno();
   an.display();
  }
}

Sample output:

Enter a limit: 500

Armstrong numbers below 500 :
1
153
370
407
Java: Armstrong Numbers up to a Limit




No comments:

Post a Comment