You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package gocircomprover
  2. import (
  3. "fmt"
  4. "math"
  5. "math/big"
  6. )
  7. type rootsT struct {
  8. roots [][]*big.Int
  9. w []*big.Int
  10. }
  11. func newRootsT() rootsT {
  12. var roots rootsT
  13. rem := new(big.Int).Sub(R, big.NewInt(1))
  14. s := 0
  15. for rem.Bit(0) == 0 { // rem.Bit==0 when even
  16. s++
  17. rem = new(big.Int).Rsh(rem, 1)
  18. }
  19. roots.w = make([]*big.Int, s+1)
  20. roots.w[s] = fExp(big.NewInt(5), rem)
  21. n := s - 1
  22. for n >= 0 {
  23. roots.w[n] = fMul(roots.w[n+1], roots.w[n+1])
  24. n--
  25. }
  26. roots.roots = make([][]*big.Int, 50) // TODO WIP
  27. roots.setRoots(15)
  28. return roots
  29. }
  30. func (roots rootsT) setRoots(n int) {
  31. for i := n; i >= 0 && nil == roots.roots[i]; i-- { // TODO tmp i<=len(r)
  32. r := big.NewInt(1)
  33. nroots := 1 << i
  34. var rootsi []*big.Int
  35. for j := 0; j < nroots; j++ {
  36. rootsi = append(rootsi, r)
  37. r = fMul(r, roots.w[i])
  38. }
  39. roots.roots[i] = rootsi
  40. }
  41. }
  42. func fft(roots rootsT, pall []*big.Int, bits, offset, step int) []*big.Int {
  43. n := 1 << bits
  44. if n == 1 {
  45. return []*big.Int{pall[offset]}
  46. } else if n == 2 {
  47. return []*big.Int{
  48. fAdd(pall[offset], pall[offset+step]), // TODO tmp
  49. fSub(pall[offset], pall[offset+step]),
  50. }
  51. }
  52. ndiv2 := n >> 1
  53. p1 := fft(roots, pall, bits-1, offset, step*2)
  54. p2 := fft(roots, pall, bits-1, offset+step, step*2)
  55. // var out []*big.Int
  56. out := make([]*big.Int, n)
  57. for i := 0; i < ndiv2; i++ {
  58. fmt.Println(i, len(roots.roots))
  59. out[i] = fAdd(p1[i], fMul(roots.roots[bits][i], p2[i]))
  60. out[i+ndiv2] = fSub(p1[i], fMul(roots.roots[bits][i], p2[i]))
  61. }
  62. return out
  63. }
  64. func ifft(p []*big.Int) []*big.Int {
  65. if len(p) <= 1 {
  66. return p
  67. }
  68. bits := math.Log2(float64(len(p)-1)) + 1
  69. roots := newRootsT()
  70. roots.setRoots(int(bits))
  71. m := 1 << int(bits)
  72. ep := extend(p, m)
  73. res := fft(roots, ep, int(bits), 0, 1)
  74. twoinvm := fInv(fMul(big.NewInt(1), big.NewInt(int64(m))))
  75. var resn []*big.Int
  76. for i := 0; i < m; i++ {
  77. resn = append(resn, fMul(res[(m-i)%m], twoinvm))
  78. }
  79. return resn
  80. }
  81. func extend(p []*big.Int, e int) []*big.Int {
  82. if e == len(p) {
  83. return p
  84. }
  85. z := arrayOfZeroes(e - len(p))
  86. return append(p, z...)
  87. }