fft.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. // Package bigfft implements multiplication of big.Int using FFT.
  2. //
  3. // The implementation is based on the Schönhage-Strassen method
  4. // using integer FFT modulo 2^n+1.
  5. package bigfft
  6. import (
  7. "math/big"
  8. "unsafe"
  9. )
  10. const _W = int(unsafe.Sizeof(big.Word(0)) * 8)
  11. type nat []big.Word
  12. func (n nat) String() string {
  13. v := new(big.Int)
  14. v.SetBits(n)
  15. return v.String()
  16. }
  17. // fftThreshold is the size (in words) above which FFT is used over
  18. // Karatsuba from math/big.
  19. //
  20. // TestCalibrate seems to indicate a threshold of 60kbits on 32-bit
  21. // arches and 110kbits on 64-bit arches.
  22. var fftThreshold = 1800
  23. // Mul computes the product x*y and returns z.
  24. // It can be used instead of the Mul method of
  25. // *big.Int from math/big package.
  26. func Mul(x, y *big.Int) *big.Int {
  27. xwords := len(x.Bits())
  28. ywords := len(y.Bits())
  29. if xwords > fftThreshold && ywords > fftThreshold {
  30. return mulFFT(x, y)
  31. }
  32. return new(big.Int).Mul(x, y)
  33. }
  34. func mulFFT(x, y *big.Int) *big.Int {
  35. var xb, yb nat = x.Bits(), y.Bits()
  36. zb := fftmul(xb, yb)
  37. z := new(big.Int)
  38. z.SetBits(zb)
  39. if x.Sign()*y.Sign() < 0 {
  40. z.Neg(z)
  41. }
  42. return z
  43. }
  44. // A FFT size of K=1<<k is adequate when K is about 2*sqrt(N) where
  45. // N = x.Bitlen() + y.Bitlen().
  46. func fftmul(x, y nat) nat {
  47. k, m := fftSize(x, y)
  48. xp := polyFromNat(x, k, m)
  49. yp := polyFromNat(y, k, m)
  50. rp := xp.Mul(&yp)
  51. return rp.Int()
  52. }
  53. // fftSizeThreshold[i] is the maximal size (in bits) where we should use
  54. // fft size i.
  55. var fftSizeThreshold = [...]int64{0, 0, 0,
  56. 4 << 10, 8 << 10, 16 << 10, // 5
  57. 32 << 10, 64 << 10, 1 << 18, 1 << 20, 3 << 20, // 10
  58. 8 << 20, 30 << 20, 100 << 20, 300 << 20, 600 << 20,
  59. }
  60. // returns the FFT length k, m the number of words per chunk
  61. // such that m << k is larger than the number of words
  62. // in x*y.
  63. func fftSize(x, y nat) (k uint, m int) {
  64. words := len(x) + len(y)
  65. bits := int64(words) * int64(_W)
  66. k = uint(len(fftSizeThreshold))
  67. for i := range fftSizeThreshold {
  68. if fftSizeThreshold[i] > bits {
  69. k = uint(i)
  70. break
  71. }
  72. }
  73. // The 1<<k chunks of m words must have N bits so that
  74. // 2^N-1 is larger than x*y. That is, m<<k > words
  75. m = words>>k + 1
  76. return
  77. }
  78. // valueSize returns the length (in words) to use for polynomial
  79. // coefficients, to compute a correct product of polynomials P*Q
  80. // where deg(P*Q) < K (== 1<<k) and where coefficients of P and Q are
  81. // less than b^m (== 1 << (m*_W)).
  82. // The chosen length (in bits) must be a multiple of 1 << (k-extra).
  83. func valueSize(k uint, m int, extra uint) int {
  84. // The coefficients of P*Q are less than b^(2m)*K
  85. // so we need W * valueSize >= 2*m*W+K
  86. n := 2*m*_W + int(k) // necessary bits
  87. K := 1 << (k - extra)
  88. if K < _W {
  89. K = _W
  90. }
  91. n = ((n / K) + 1) * K // round to a multiple of K
  92. return n / _W
  93. }
  94. // poly represents an integer via a polynomial in Z[x]/(x^K+1)
  95. // where K is the FFT length and b^m is the computation basis 1<<(m*_W).
  96. // If P = a[0] + a[1] x + ... a[n] x^(K-1), the associated natural number
  97. // is P(b^m).
  98. type poly struct {
  99. k uint // k is such that K = 1<<k.
  100. m int // the m such that P(b^m) is the original number.
  101. a []nat // a slice of at most K m-word coefficients.
  102. }
  103. // polyFromNat slices the number x into a polynomial
  104. // with 1<<k coefficients made of m words.
  105. func polyFromNat(x nat, k uint, m int) poly {
  106. p := poly{k: k, m: m}
  107. length := len(x)/m + 1
  108. p.a = make([]nat, length)
  109. for i := range p.a {
  110. if len(x) < m {
  111. p.a[i] = make(nat, m)
  112. copy(p.a[i], x)
  113. break
  114. }
  115. p.a[i] = x[:m]
  116. x = x[m:]
  117. }
  118. return p
  119. }
  120. // Int evaluates back a poly to its integer value.
  121. func (p *poly) Int() nat {
  122. length := len(p.a)*p.m + 1
  123. if na := len(p.a); na > 0 {
  124. length += len(p.a[na-1])
  125. }
  126. n := make(nat, length)
  127. m := p.m
  128. np := n
  129. for i := range p.a {
  130. l := len(p.a[i])
  131. c := addVV(np[:l], np[:l], p.a[i])
  132. if np[l] < ^big.Word(0) {
  133. np[l] += c
  134. } else {
  135. addVW(np[l:], np[l:], c)
  136. }
  137. np = np[m:]
  138. }
  139. n = trim(n)
  140. return n
  141. }
  142. func trim(n nat) nat {
  143. for i := range n {
  144. if n[len(n)-1-i] != 0 {
  145. return n[:len(n)-i]
  146. }
  147. }
  148. return nil
  149. }
  150. // Mul multiplies p and q modulo X^K-1, where K = 1<<p.k.
  151. // The product is done via a Fourier transform.
  152. func (p *poly) Mul(q *poly) poly {
  153. // extra=2 because:
  154. // * some power of 2 is a K-th root of unity when n is a multiple of K/2.
  155. // * 2 itself is a square (see fermat.ShiftHalf)
  156. n := valueSize(p.k, p.m, 2)
  157. pv, qv := p.Transform(n), q.Transform(n)
  158. rv := pv.Mul(&qv)
  159. r := rv.InvTransform()
  160. r.m = p.m
  161. return r
  162. }
  163. // A polValues represents the value of a poly at the powers of a
  164. // K-th root of unity θ=2^(l/2) in Z/(b^n+1)Z, where b^n = 2^(K/4*l).
  165. type polValues struct {
  166. k uint // k is such that K = 1<<k.
  167. n int // the length of coefficients, n*_W a multiple of K/4.
  168. values []fermat // a slice of K (n+1)-word values
  169. }
  170. // Transform evaluates p at θ^i for i = 0...K-1, where
  171. // θ is a K-th primitive root of unity in Z/(b^n+1)Z.
  172. func (p *poly) Transform(n int) polValues {
  173. k := p.k
  174. inputbits := make([]big.Word, (n+1)<<k)
  175. input := make([]fermat, 1<<k)
  176. // Now computed q(ω^i) for i = 0 ... K-1
  177. valbits := make([]big.Word, (n+1)<<k)
  178. values := make([]fermat, 1<<k)
  179. for i := range values {
  180. input[i] = inputbits[i*(n+1) : (i+1)*(n+1)]
  181. if i < len(p.a) {
  182. copy(input[i], p.a[i])
  183. }
  184. values[i] = fermat(valbits[i*(n+1) : (i+1)*(n+1)])
  185. }
  186. fourier(values, input, false, n, k)
  187. return polValues{k, n, values}
  188. }
  189. // InvTransform reconstructs p (modulo X^K - 1) from its
  190. // values at θ^i for i = 0..K-1.
  191. func (v *polValues) InvTransform() poly {
  192. k, n := v.k, v.n
  193. // Perform an inverse Fourier transform to recover p.
  194. pbits := make([]big.Word, (n+1)<<k)
  195. p := make([]fermat, 1<<k)
  196. for i := range p {
  197. p[i] = fermat(pbits[i*(n+1) : (i+1)*(n+1)])
  198. }
  199. fourier(p, v.values, true, n, k)
  200. // Divide by K, and untwist q to recover p.
  201. u := make(fermat, n+1)
  202. a := make([]nat, 1<<k)
  203. for i := range p {
  204. u.Shift(p[i], -int(k))
  205. copy(p[i], u)
  206. a[i] = nat(p[i])
  207. }
  208. return poly{k: k, m: 0, a: a}
  209. }
  210. // NTransform evaluates p at θω^i for i = 0...K-1, where
  211. // θ is a (2K)-th primitive root of unity in Z/(b^n+1)Z
  212. // and ω = θ².
  213. func (p *poly) NTransform(n int) polValues {
  214. k := p.k
  215. if len(p.a) >= 1<<k {
  216. panic("Transform: len(p.a) >= 1<<k")
  217. }
  218. // θ is represented as a shift.
  219. θshift := (n * _W) >> k
  220. // p(x) = a_0 + a_1 x + ... + a_{K-1} x^(K-1)
  221. // p(θx) = q(x) where
  222. // q(x) = a_0 + θa_1 x + ... + θ^(K-1) a_{K-1} x^(K-1)
  223. //
  224. // Twist p by θ to obtain q.
  225. tbits := make([]big.Word, (n+1)<<k)
  226. twisted := make([]fermat, 1<<k)
  227. src := make(fermat, n+1)
  228. for i := range twisted {
  229. twisted[i] = fermat(tbits[i*(n+1) : (i+1)*(n+1)])
  230. if i < len(p.a) {
  231. for i := range src {
  232. src[i] = 0
  233. }
  234. copy(src, p.a[i])
  235. twisted[i].Shift(src, θshift*i)
  236. }
  237. }
  238. // Now computed q(ω^i) for i = 0 ... K-1
  239. valbits := make([]big.Word, (n+1)<<k)
  240. values := make([]fermat, 1<<k)
  241. for i := range values {
  242. values[i] = fermat(valbits[i*(n+1) : (i+1)*(n+1)])
  243. }
  244. fourier(values, twisted, false, n, k)
  245. return polValues{k, n, values}
  246. }
  247. // InvTransform reconstructs a polynomial from its values at
  248. // roots of x^K+1. The m field of the returned polynomial
  249. // is unspecified.
  250. func (v *polValues) InvNTransform() poly {
  251. k := v.k
  252. n := v.n
  253. θshift := (n * _W) >> k
  254. // Perform an inverse Fourier transform to recover q.
  255. qbits := make([]big.Word, (n+1)<<k)
  256. q := make([]fermat, 1<<k)
  257. for i := range q {
  258. q[i] = fermat(qbits[i*(n+1) : (i+1)*(n+1)])
  259. }
  260. fourier(q, v.values, true, n, k)
  261. // Divide by K, and untwist q to recover p.
  262. u := make(fermat, n+1)
  263. a := make([]nat, 1<<k)
  264. for i := range q {
  265. u.Shift(q[i], -int(k)-i*θshift)
  266. copy(q[i], u)
  267. a[i] = nat(q[i])
  268. }
  269. return poly{k: k, m: 0, a: a}
  270. }
  271. // fourier performs an unnormalized Fourier transform
  272. // of src, a length 1<<k vector of numbers modulo b^n+1
  273. // where b = 1<<_W.
  274. func fourier(dst []fermat, src []fermat, backward bool, n int, k uint) {
  275. var rec func(dst, src []fermat, size uint)
  276. tmp := make(fermat, n+1) // pre-allocate temporary variables.
  277. tmp2 := make(fermat, n+1) // pre-allocate temporary variables.
  278. // The recursion function of the FFT.
  279. // The root of unity used in the transform is ω=1<<(ω2shift/2).
  280. // The source array may use shifted indices (i.e. the i-th
  281. // element is src[i << idxShift]).
  282. rec = func(dst, src []fermat, size uint) {
  283. idxShift := k - size
  284. ω2shift := (4 * n * _W) >> size
  285. if backward {
  286. ω2shift = -ω2shift
  287. }
  288. // Easy cases.
  289. if len(src[0]) != n+1 || len(dst[0]) != n+1 {
  290. panic("len(src[0]) != n+1 || len(dst[0]) != n+1")
  291. }
  292. switch size {
  293. case 0:
  294. copy(dst[0], src[0])
  295. return
  296. case 1:
  297. dst[0].Add(src[0], src[1<<idxShift]) // dst[0] = src[0] + src[1]
  298. dst[1].Sub(src[0], src[1<<idxShift]) // dst[1] = src[0] - src[1]
  299. return
  300. }
  301. // Let P(x) = src[0] + src[1<<idxShift] * x + ... + src[K-1 << idxShift] * x^(K-1)
  302. // The P(x) = Q1(x²) + x*Q2(x²)
  303. // where Q1's coefficients are src with indices shifted by 1
  304. // where Q2's coefficients are src[1<<idxShift:] with indices shifted by 1
  305. // Split destination vectors in halves.
  306. dst1 := dst[:1<<(size-1)]
  307. dst2 := dst[1<<(size-1):]
  308. // Transform Q1 and Q2 in the halves.
  309. rec(dst1, src, size-1)
  310. rec(dst2, src[1<<idxShift:], size-1)
  311. // Reconstruct P's transform from transforms of Q1 and Q2.
  312. // dst[i] is dst1[i] + ω^i * dst2[i]
  313. // dst[i + 1<<(k-1)] is dst1[i] + ω^(i+K/2) * dst2[i]
  314. //
  315. for i := range dst1 {
  316. tmp.ShiftHalf(dst2[i], i*ω2shift, tmp2) // ω^i * dst2[i]
  317. dst2[i].Sub(dst1[i], tmp)
  318. dst1[i].Add(dst1[i], tmp)
  319. }
  320. }
  321. rec(dst, src, k)
  322. }
  323. // Mul returns the pointwise product of p and q.
  324. func (p *polValues) Mul(q *polValues) (r polValues) {
  325. n := p.n
  326. r.k, r.n = p.k, p.n
  327. r.values = make([]fermat, len(p.values))
  328. bits := make([]big.Word, len(p.values)*(n+1))
  329. buf := make(fermat, 8*n)
  330. for i := range r.values {
  331. r.values[i] = bits[i*(n+1) : (i+1)*(n+1)]
  332. z := buf.Mul(p.values[i], q.values[i])
  333. copy(r.values[i], z)
  334. }
  335. return
  336. }