What is an Armstrong Number?
A Number is Armstrong, if the sum of the cubes of the digits of number is equal to the number itself.
Example:
153=(1*1*1) + (5*5*5) + (3*3*3) =153
1, 153, 370, 371, 407 are possible Armstrong numbers under 1000.
Java Code to find Armstrong numbers ranging between 1 to n.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import java.util.Scanner; public class Armstrong { static boolean armstrong(int n) { int sum = 0; int r; int num = n; while (n!=0) { r = n%10; sum = sum+(r*r*r); n = n/10; } if (sum == num) return true ; else return false ; } public static void main(String[] args) { Scanner obj = new Scanner(System. in ); System.out.println( "enter the value for n" ); int n = obj.nextInt(); for (int i=1; i<=n; i++) { if (armstrong(i)) System.out.println(i); } } } |
Output:
>enter the value for n 500 1 153 370 371 407
No comments:
Post a Comment