multiplicative inverse of modulo m in scheme

后端 未结 4 1096
自闭症患者
自闭症患者 2021-01-23 16:58

I\'ve written the code for multiplicative inverse of modulo m. It works for most of the initial cases but not for some. The code is below:

(define (inverse x m)
         


        
4条回答
  •  太阳男子
    2021-01-23 17:08

    The algorithm you quoted is Algorithm 9.4.4 from the book Prime Numbers by Richard Crandall and Carl Pomerance. In the text of the book they state that the algorithm works for both prime and composite moduli, but in the errata to their book they correctly state that the algorithm works always for prime moduli and mostly, but not always, for composite moduli. Hence the failure that you found.

    Like you, I used Algorithm 9.4.4 and was mystified at some of my results until I discovered the problem.

    Here's the modular inverse function that I use now, which works with both prime and composite moduli, as long as its two arguments are coprime to one another. It is essentially the extended Euclidean algorithm that @OscarLopez uses, but with some redundant calculations stripped out. If you like, you can change the function to return #f instead of throwing an error.

    (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)))))))
    

提交回复
热议问题