-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem34.go
More file actions
61 lines (56 loc) · 1.46 KB
/
Copy pathproblem34.go
File metadata and controls
61 lines (56 loc) · 1.46 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
60
61
package projecteuler
// first converts given number into a slice
// of digits, then each digit is updated with its corresponding
// factorial values, which is precomputed in a map, simply looking up
// from that buffer will be enough
func digitFactorial(num int, buffer *map[int]int) []int {
tmp := splitDigits(num)
for i := range tmp {
tmp[i] = (*buffer)[tmp[i]]
}
return tmp
}
// computes sum of items of a slice i.e.
// returns sum of computed slice by previous function
func digitFactorialSum(arr []int) int {
sum := 0
for _, i := range arr {
sum += i
}
return sum
}
// checks whether a given number is curious number
// or not
func isCuriousNumber(num int, buffer *map[int]int) bool {
return num == digitFactorialSum(digitFactorial(num, buffer))
}
// creates a hash map, holding factorial of all digits
// of decimal number system, which will be used
// for looking up factorial value of certain digit, while
// computing digit factorial sum
func makeFactorialBuffer() map[int]int {
factorial := func(n int) int {
prod := 1
for i := n; i > 1; i-- {
prod *= i
}
return prod
}
buffer := make(map[int]int)
for i := 0; i < 10; i++ {
buffer[i] = factorial(i)
}
return buffer
}
// DigitFactorial - Computes sum of all curious numbers
// NOTE: there are only two curious numbers 145 & 40225
func DigitFactorial() int {
buffer := makeFactorialBuffer()
sum := 0
for i := 10; i < 41000; i++ {
if isCuriousNumber(i, &buffer) {
sum += i
}
}
return sum
}