Haskell中的快速Pollard Rho分解

时间:2016-06-01 05:01:35

标签: algorithm haskell math prime-factoring

我正在尝试在Haskell中实现Pollard Rho分解方法。 这是我来的地方

func :: Int -> Int -> Int
func x n = mod ( x * x - 1) n

pollardStep :: Int -> Int -> Int -> Int -> Int -> Int
pollardStep i k n x y
      | d /= 1 && d /= n = d
      | i == k = pollardStep (i+1) (2*k) n x1 x1
      | otherwise = pollardStep (i+1) k n x1 y
      where d = gcd n $ abs $ y - x
            x1 = func x n

pollard_rho :: Int -> Int
pollard_rho n = pollardStep 1 2 n 2 2

此功能如果适用于像8051这样的小数字。 但是当我试图找到大数的因子时,例如,1724114033281923457(我已经检查过,它与因子11363592254和1229739323是复合的)它需要永远(在这种情况下,函数永远不会结束)。 我究竟做错了什么?我会非常感谢任何帮助。

1 个答案:

答案 0 :(得分:7)

据我所知,当 X Y Z condition count 0 -3 6 -7 NaN NaN 1 -4 -10 -1 NaN NaN 2 9 -10 -9 2.0 0.0 3 5 0 -8 3.0 0.0 4 -2 1 -8 3.0 NaN 5 6 -6 -3 5.0 1.0 6 0 6 3 5.0 NaN 7 -6 -7 -6 5.0 NaN 8 7 -2 -5 8.0 0.0 9 0 -1 5 8.0 NaN 10 5 8 -3 10.0 0.0 11 -2 -2 1 10.0 NaN 12 3 4 2 12.0 1.0 13 -5 1 -9 12.0 NaN 14 -7 2 6 12.0 NaN 15 1 -10 6 15.0 0.0 16 1 -8 6 16.0 0.0 17 -4 -9 -8 16.0 NaN 18 -9 4 6 16.0 NaN 19 5 -6 2 19.0 0.0 20 5 7 -1 20.0 0.0 21 2 -2 -3 21.0 0.0 22 -6 -10 -2 21.0 NaN 23 -7 -9 3 21.0 NaN 24 -8 7 -8 21.0 NaN 25 3 -3 6 25.0 0.0 26 1 -6 -3 26.0 1.0 27 -4 6 -1 26.0 NaN 28 6 -4 9 28.0 0.0 29 -8 2 1 28.0 NaN .. .. .. .. ... ... 70 -5 7 -6 68.0 NaN 71 6 6 -7 71.0 1.0 72 -3 0 3 71.0 NaN 73 -5 3 2 71.0 NaN 74 -6 -8 8 71.0 NaN 75 1 0 -4 75.0 0.0 76 7 -9 -5 76.0 0.0 77 1 0 -1 77.0 0.0 78 5 9 -2 78.0 0.0 79 -8 -9 -6 78.0 NaN 80 2 -3 3 80.0 3.0 81 -7 -5 8 80.0 NaN 82 -4 -5 -7 80.0 NaN 83 -3 5 -6 80.0 NaN 84 -5 1 4 80.0 NaN 85 -1 6 7 80.0 NaN 86 -7 4 4 80.0 NaN 87 -7 -4 -1 80.0 NaN 88 -2 -8 2 80.0 NaN 89 4 6 4 89.0 0.0 90 4 -10 -8 90.0 0.0 91 -7 -9 5 90.0 NaN 92 5 3 -1 92.0 0.0 93 6 6 6 93.0 0.0 94 9 -2 0 94.0 1.0 95 -1 5 5 94.0 NaN 96 2 8 -9 96.0 2.0 97 -6 7 -4 96.0 NaN 98 -1 7 -8 96.0 NaN 99 -4 0 -1 96.0 NaN 的数字过大时,问题可能会出现溢出 - 在这种情况下很可能是Int x * x - 1部分(func在我的系统上有Int 9223372036854775807)

所以最简单的选择就是切换到maxBound无处不在的地方:

Integer

这当然会使一切变得有点慢