|
1 | 1 | packageOthers; |
2 | 2 |
|
3 | | -importjava.util.Scanner; |
4 | | - |
5 | 3 | /** |
6 | | - * A utility to check if a given number is armstrong or not. Armstrong number is |
7 | | - * a number that is equal to the sum of cubes of its digits for example 0, 1, |
8 | | - * 153, 370, 371, 407 etc. For example 153 = 1^3 + 5^3 +3^3 |
9 | | - * |
10 | | - * @author mani manasa mylavarapu |
| 4 | + * An Armstrong number is equal to the sum of the cubes of its digits. |
| 5 | + * For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. |
| 6 | + * An Armstrong number is often called Narcissistic number. |
11 | 7 | */ |
12 | 8 | publicclassArmstrong { |
13 | | -staticScannerscan; |
14 | 9 |
|
15 | 10 | publicstaticvoidmain(String[]args) { |
16 | | -scan =newScanner(System.in); |
17 | | -intn =inputInt("please enter the number"); |
18 | | -booleanisArmstrong =checkIfANumberIsAmstrongOrNot(n); |
19 | | -if (isArmstrong) { |
20 | | -System.out.println("the number is armstrong"); |
21 | | - }else { |
22 | | -System.out.println("the number is not armstrong"); |
23 | | - } |
| 11 | +assert (isArmStrong(0)); |
| 12 | +assert (isArmStrong(1)); |
| 13 | +assert (isArmStrong(153)); |
| 14 | +assert (isArmStrong(1634)); |
| 15 | +assert (isArmStrong(371)); |
| 16 | +assert (!isArmStrong(200)); |
24 | 17 | } |
25 | 18 |
|
26 | 19 | /** |
27 | | - * Checks whether a given number is an armstrong number or not. Armstrong |
28 | | - * number is a number that is equal to the sum of cubes of its digits for |
29 | | - * example 0, 1, 153, 370, 371, 407 etc. |
| 20 | + * Checks whether a given number is an armstrong number or not. |
30 | 21 | * |
31 | | - * @param number |
32 | | - * @returnboolean |
| 22 | + * @param number number to check |
| 23 | + * @return{@code true} if given number is armstrong number, {@code false} otherwise |
33 | 24 | */ |
34 | | -publicstaticbooleancheckIfANumberIsAmstrongOrNot(intnumber) { |
35 | | -intremainder,sum =0,temp =0; |
36 | | -temp =number; |
| 25 | +privatestaticbooleanisArmStrong(intnumber) { |
| 26 | +intsum =0; |
| 27 | +inttemp =number; |
| 28 | +intnumberOfDigits =0; |
| 29 | +while (temp !=0) { |
| 30 | +numberOfDigits++; |
| 31 | +temp /=10; |
| 32 | + } |
| 33 | +temp =number;/* copy number again */ |
37 | 34 | while (number >0) { |
38 | | -remainder =number %10; |
39 | | -sum =sum + (remainder *remainder *remainder); |
40 | | -number =number /10; |
| 35 | +intremainder =number %10; |
| 36 | +intpower =1; |
| 37 | +for (inti =1;i <=numberOfDigits;power *=remainder, ++i) ; |
| 38 | +sum =sum +power; |
| 39 | +number /=10; |
41 | 40 | } |
42 | 41 | returnsum ==temp; |
43 | 42 | } |
44 | | - |
45 | | -privatestaticintinputInt(Stringstring) { |
46 | | -System.out.print(string); |
47 | | -returnInteger.parseInt(scan.nextLine()); |
48 | | - } |
49 | 43 | } |