- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
59 lines (47 loc) · 1.47 KB
/
Copy pathMain.java
File metadata and controls
59 lines (47 loc) · 1.47 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
57
58
59
importjava.util.HashMap;
/*
@author: mc-es
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.
Answer: 40730
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
intsum = 0;
HashMap<Integer, Integer> factorials = newHashMap<>();
// Calculate factorials for each digit from 0 to 9 and store in the HashMap
for (inti = 0; i <= 9; i++) {
factorials.put(i, factorial(i));
}
// Find the upper bound for the range of numbers to check
intupperBound = 7 * factorials.get(9);
// Check each number to see if it equals the sum of the factorials of its digits
for (inti = 10; i <= upperBound; i++) {
if (isFactorialSum(i, factorials)) {
sum += i;
}
}
System.out.println(sum);
}
// Calculate the factorial of a given number
publicstaticintfactorial(intn) {
if (n == 0) {
return1;
}
intresult = 1;
for (inti = 1; i <= n; i++) {
result *= i;
}
returnresult;
}
// Check if the sum of factorials of the digits of a number is equal to the number itself
publicstaticbooleanisFactorialSum(intnum, HashMap<Integer, Integer> factorials) {
intsum = 0;
for (charc : Integer.toString(num).toCharArray()) {
sum += factorials.get(Character.getNumericValue(c));
}
returnnum == sum;
}
}