模块化逆算法

时间:2012-10-29 11:17:15

标签: algorithm scheme

  

可能重复:
  multiplicative inverse of modulo m in scheme

我已经编写了一个代码,用于找到将x和y解析为一对。 我需要编写一个模块化的逆代码,使用ax + by = 1找到e modulo n的乘法逆。

  

块引用

(define (ax+by=1 a b)
        (if (= b 0)
            (cons 1 0)
            (let* ((q (quotient a b))
                   (r (remainder a b))
                   (e (ax+by=1 b r))
                   (s (car e))
                   (t (cdr e)))
           (cons t (- s (* q t))))))

编辑:问题解决了以下功能。

  

Blockquote

 (define inverse-mod (lambda (a m) 
                  (if (not (= 1 (gcd a m)))
                      (display "**Error** No inverse exists.")
                      (if (> 0(car (ax+by=1 a m)))
                          (+ (car (ax+by=1 a m)) m)
                          (car (ax+by=1 a m))))))

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

这使用扩展的欧几里德算法来找到模逆:

(define (inverse x m)
  (let loop ((x x) (b m) (a 0) (u 1))
    (if (zero? x)
        (if (= b 1) (modulo a m)
          (error 'inverse "must be coprime"))
        (let* ((q (quotient b x)))
          (loop (modulo b x) x u (- a (* u q)))))))