-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodular_cyclotomic_polynomial.sf
More file actions
40 lines (28 loc) · 985 Bytes
/
modular_cyclotomic_polynomial.sf
File metadata and controls
40 lines (28 loc) · 985 Bytes
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
#!/usr/bin/ruby
# Daniel "Trizen" Șuteu
# Date: 27 May 2019
# https://github.com/trizen
# Efficient formula for computing the n-th cyclotomic polynomial.
# Formula:
# cyclotomic(n, x) = Prod_{d|n} (x^(n/d) - 1)^moebius(d)
# Optimization: by generating only the squarefree divisors of n and keeping track of
# the number of prime factors of each divisor, we do not need the Moebius function.
# See also:
# https://en.wikipedia.org/wiki/Cyclotomic_polynomial
func modular_cyclotomic_polynomial(n, x, m) {
var d = []
for p in (n.factor.uniq) {
d << d.map_2d {|q,e| [(p*q)%m, e+1] }...
d << [p, 1]
}
d << [1, 0]
var prod = 1
for p,e in (d) {
var t = powmod(x, n/p, m)-1
t = invmod(t, m) if e.is_odd
prod *= t #=
prod %= m #=
}
return prod
}
say 20.of { modular_cyclotomic_polynomial(_, 2, 2017) } #=> [0, 1, 3, 7, 5, 31, 3, 127, 17, 73, 11, 30, 13, 123, 43, 151, 257, 1983, 57, 1884]