Scheme code for Pollard's Rho algorithm

时间:2015-04-23 05:29:20

标签: scheme

I am trying to learn scheme by implementing few algorithms.

Pollards-Rho(n)
 g(x) = x2 + 1 mod n
    x ← 2; y ← 2; d ← 1;
    While d = 1:
        x ← g(x)
        y ← g(g(y))
        d ← gcd(|x - y|, n)
    If d = n, return failure.
    Else, return d

I am trying to implement the above algorithm in scheme. Any help would be appreciated. Thanks

1 个答案:

答案 0 :(得分:6)

Racket中的实现:

;;; ALGORITHM 19.8  Pollard's rho method
; INPUT   n>=3 neither a prime nor a perfect power
; OUTPUT  Either a proper divisor of n or #f
(: pollard : Natural -> (U Natural False))
(define (pollard n)
  (let ([x0 (random-natural n)])
    (do ([xi x0 (remainder (+ (* xi xi) 1) n)]
         [yi x0 (remainder (+ (sqr (+ (* yi yi) 1)) 1) n)]
         [i  0  (add1 i)]
         [g  1  (gcd (- xi yi) n)])
      [(or (< 1 g n) (> i (sqrt n)))
       (if (< 1 g n)
           (cast g natural?)
           #f)])))