8000 Merge pull request #34 from naresh1406/master · RockLee444/Java-Algorithms@43cc14b · GitHub
[go: up one dir, main page]

Skip to content

Commit 43cc14b

Browse files
authored
Merge pull request darpanjbora#34 from naresh1406/master
Armstrong Number algorithm
2 parents aef6661 + 8add2f8 commit 43cc14b

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Miscellaneous/ArmstrongNumber.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/**
2+
* Created with IntelliJ IDEA.
3+
* User: ngupta
4+
* Date: 14/10/19
5+
* Time: 1:12 AM
6+
*/
7+
8+
/**
9+
Armstrong number is a number that is equal to the sum of cubes of its digits.
10+
For example 0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
11+
12+
*/
13+
public class ArmstrongNumber {
14+
public static void main(String[] args) {
15+
int start = 0;
16+
int end = 1000000;
17+
18+
//print all the armstrong numnbers from 0 to 1000000
19+
printArmstrongNumbers(start, end);
20+
}
21+
22+
public static void printArmstrongNumbers(int start, int end) {
23+
for (int i = start; i < end; i++) {
24+
if (isArmstrong(i))
25+
System.out.println(i);
26+
}
27+
}
28+
29+
public static boolean isArmstrong(int n) {
30+
31+
if (n < 10)
32+
return true;
33+
34+
int length = numberLength(n);
35+
36+
int num = 0;
37+
int nCopy = n;
38+
int digit;
39+
40+
while (n > 0) {
41+
digit = n % 10;
42+
num += Math.pow(digit, length);
43+
n /= 10;
44+
}
45+
46+
return nCopy == num;
47+
}
48+
49+
public static int numberLength(int n) {
50+
int len = 0;
51+
while (n > 0) {
52+
len++;
53+
n /= 10;
54+
}
55+
return len;
56+
}
57+
}

0 commit comments

Comments
 (0)
0