multiplicative inverse of modulo m in scheme

后端 未结 4 1100
自闭症患者
自闭症患者 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:18

    Does it have to be precisely that algorithm? if not, try this one, taken from wikibooks:

    (define (egcd a b)
      (if (zero? a)
          (values b 0 1)
          (let-values (((g y x) (egcd (modulo b a) a)))
            (values g (- x (* (quotient b a) y)) y))))
    
    (define (modinv a m)
      (let-values (((g x y) (egcd a m)))
        (if (not (= g 1))
            #f
            (modulo x m))))
    

    It works as expected:

    (modinv 5 11) ; 9
    (modinv 9 11) ; 5
    (modinv 7 11) ; 8
    (modinv 8 12) ; #f 
    (modinv 5 12) ; 5
    

提交回复
热议问题