Skip to content

Instantly share code, notes, and snippets.

@allnightlong
Last active October 6, 2016 17:19
Show Gist options
  • Save allnightlong/c382bb9c5b8582525aec9aa7b87a07b6 to your computer and use it in GitHub Desktop.
Save allnightlong/c382bb9c5b8582525aec9aa7b87a07b6 to your computer and use it in GitHub Desktop.
package minfact
import com.google.common.base.Stopwatch
import groovy.transform.CompileStatic
import groovy.transform.Memoized
import java.util.concurrent.TimeUnit
@CompileStatic
public class MinFact {
static int s(int n) {
def nMultipliers = multipliers(n).collect()
def index = 0
while (nMultipliers) {
index = index < nMultipliers.min() ? nMultipliers.min() : ++index
def iMultipliers = multipliers(index)
iMultipliers.each {
nMultipliers.removeElement(it)
}
}
index
}
@Memoized
protected static List<Integer> multipliers(int n) {
if (n == 1) {
return []
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return [i].plus(multipliers(n / i as int))
}
}
return [n]
}
protected static s(int from, int to) {
def result = 0G
(from..to).each {
def s = s(it)
result += s
println "$it -> $s $result"
}
result
}
public static void main(String[] args) {
def from = 2_300_000
def to = 2_400_000
def stopwatch = Stopwatch.createStarted()
println s(from, to)
println stopwatch.elapsed(TimeUnit.MILLISECONDS)
}
}
package minfact
import spock.lang.Specification
class MinFactTest extends Specification {
def s() {
expect:
MinFact.s(n) == result
where:
n | result
1 | 0
2 | 2
3 | 3
4 | 4
5 | 5
6 | 3
7 | 7
8 | 4
9 | 6
10 | 5
11 | 11
12 | 4
13 | 13
14 | 7
15 | 5
16 | 6
17 | 17
18 | 6
19 | 19
20 | 5
21 | 7
22 | 11
23 | 23
24 | 4
25 | 10
26 | 13
27 | 9
28 | 7
29 | 29
30 | 5
31 | 31
32 | 8
33 | 11
34 | 17
35 | 7
36 | 6
37 | 37
38 | 19
39 | 13
40 | 5
41 | 41
42 | 7
43 | 43
44 | 11
45 | 6
46 | 23
47 | 47
48 | 6
49 | 14
50 | 10
51 | 17
52 | 13
53 | 53
54 | 9
55 | 11
56 | 7
57 | 19
58 | 29
59 | 59
60 | 5
61 | 61
62 | 31
63 | 7
64 | 8
65 | 13
66 | 11
67 | 67
68 | 17
69 | 23
70 | 7
71 | 71
72 | 6
73 | 73
74 | 37
75 | 10
76 | 19
77 | 11
78 | 13
79 | 79
80 | 6
81 | 9
82 | 41
83 | 83
84 | 7
85 | 17
86 | 43
87 | 29
88 | 11
89 | 89
90 | 6
91 | 13
92 | 23
93 | 31
94 | 47
95 | 19
96 | 8
97 | 97
98 | 14
99 | 11
100 | 10
}
def multipliers() {
expect:
MinFact.multipliers(n) == result
where:
n | result
2 | [2]
3 | [3]
4 | [2, 2]
5 | [5]
6 | [2, 3]
7 | [7]
8 | [2, 2, 2]
9 | [3, 3]
10 | [2, 5]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment