-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoessner_miracle.sf
60 lines (44 loc) · 1.4 KB
/
moessner_miracle.sf
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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 23 July 2021
# https://github.com/trizen
# Simple implementation of the Moessner extension for computing k-th powers of integers and factorials, using only addition.
# See also the following Mathlogger video:
# The Moessner Miracle. Why wasn't this discovered for over 2000 years?
# https://www.youtube.com/watch?v=rGlpyFHfMgI
func moessner(n, k=2) {
var arr = @(1..n)
for (true; k > 1; --k) {
arr = gather {
var acc = 0
arr.each_kv {|i,v|
if (!(k `divides` (i+1))) {
take(acc += v)
}
}
}
}
return arr
}
say moessner(20, 2) #=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
say moessner(20, 3) #=> [1, 8, 27, 64, 125, 216, 343]
say moessner(20, 4) #=> [1, 16, 81, 256, 625]
say moessner(20, 5) #=> [1, 32, 243, 1024]
func moessner_factorial(n) {
var arr = @(1..n)
var factorials = []
while (arr.len) {
factorials << arr.head
arr = gather {
var acc = 0
arr.each_kv {|k,v|
if (!is_polygonal(k+1, 3)) {
take(acc += v)
}
}
}
}
return factorials
}
say ''
say moessner_factorial(polygonal(14, 3)) #=> [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200]