-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDigitFactorials.java
More file actions
56 lines (47 loc) · 1.26 KB
/
DigitFactorials.java
File metadata and controls
56 lines (47 loc) · 1.26 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package problem34;
/*
Digit factorials
Problem 34
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial
of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.
*/
public class DigitFactorials {
private static int[] factorials = new int[10];
static {
factorials[0] = 1;
}
private static int upperBound;
public static void main(String[] args) {
// generate factorials
for (int i = 1; i < 10; i++) {
factorials[i] = i * factorials[i - 1];
}
upperBound = 7 * factorials[9];
// search
int sum = 0;
for (int i = 3; i < upperBound; i++) {
String s = (String.valueOf(i));
int value = i;
int desiredDigit = value;
for (int j = 0; j < s.length(); j++, desiredDigit /= 10) {
value -= factorials[desiredDigit % 10];
}
if (value == 0) {
sum += i;
}
}
System.out.println(sum);
}
public static int factorial(int number) {
if (number == 0) {
return 1;
}
int value = 1;
while (number != 1) {
value *= number--;
}
return value;
}
}