1 | class Bug |
---|
2 | def _isPrime(candidate as int) as bool is shared |
---|
3 | if candidate & 1 == 0 |
---|
4 | return candidate == 2 |
---|
5 | i = 3 |
---|
6 | while i*i <= candidate |
---|
7 | if candidate % i == 0, return false |
---|
8 | i = i + 2 |
---|
9 | return candidate <> 1 |
---|
10 | |
---|
11 | #port of http://labs.kaliko.com/2010/03/cache-functions-in-c-using-memoization.html |
---|
12 | sig Function(param as int) as bool |
---|
13 | |
---|
14 | def memoize(func as Function) as Function |
---|
15 | cache = Dictionary<of int, bool>() |
---|
16 | return do(arg as int) |
---|
17 | result = false |
---|
18 | if cache.containsKey(arg) |
---|
19 | result = cache[arg] |
---|
20 | else |
---|
21 | result = cache[arg] = func(arg) |
---|
22 | return result |
---|
23 | |
---|
24 | |
---|
25 | def _isPrimeFast(candidate as int) as bool is shared |
---|
26 | if candidate & 1 == 0 |
---|
27 | return candidate == 2 |
---|
28 | i = 3 |
---|
29 | while i*i <= candidate |
---|
30 | if candidate % i == 0, return false |
---|
31 | i = i + 2 |
---|
32 | return candidate <> 1 |
---|
33 | |
---|
34 | |
---|
35 | def main |
---|
36 | loops = 10000000 |
---|
37 | sw = System.Diagnostics.Stopwatch() |
---|
38 | sw.start |
---|
39 | #String Builder |
---|
40 | r = List<of bool>() |
---|
41 | for i in loops |
---|
42 | r.add(_isPrime(i)) |
---|
43 | r.clear |
---|
44 | for i in loops |
---|
45 | r.add(_isPrime(i)) |
---|
46 | sw.stop |
---|
47 | GC.collect |
---|
48 | print 'Elapsed Time:[sw.elapsedMilliseconds] ms' |
---|
49 | sw.reset |
---|
50 | sw.start |
---|
51 | isPrime = .memoize<of int,bool>(ref _isPrimeFast) |
---|
52 | sr = List<of bool>() |
---|
53 | for i in loops |
---|
54 | sr.add(isPrime(i) ) |
---|
55 | sr.clear |
---|
56 | for i in loops |
---|
57 | sr.add(isPrime(i) ) |
---|
58 | sw.stop |
---|
59 | print _isPrime(10) |
---|
60 | print _isPrimeFast(10) |
---|
61 | print _isPrime(17) |
---|
62 | print _isPrimeFast(17) |
---|
63 | print _isPrime(1027) |
---|
64 | print _isPrimeFast(1027) |
---|
65 | print _isPrime(1038) |
---|
66 | print _isPrimeFast(1038) |
---|
67 | print sr.count |
---|
68 | print 'Elapsed Time:[sw.elapsedMilliseconds] ms' |
---|
69 | |
---|
70 | return |
---|