algorithm - 如何实现扩展欧几里得算法?

标签 algorithm function scheme

我如何实现 Extended Euclidean algorithm ?这是我的第一次尝试:

(define ex-gcd a b 
 ; gcd(a,b) = a * x+ b * y 
 ; gcd(a,b)-> always will be 1
 output: (x.y) 
)

最佳答案

算法对here在维基百科中,你只需要调整它只返回 Bézout 系数,返回的 cons-cell 的 car 部分将是 x,并且cdr 将是 y:

(define (extended-gcd a b)
  (let loop ([s 0] [t 1] [r b]
             [old-s 1] [old-t 0] [old-r a])
    (if (zero? r)
        (cons old-s old-t)
        (let ((q (quotient old-r r)))
          (loop (- old-s (* q s))
                (- old-t (* q t))
                (- old-r (* q r))
                s t r)))))

使用Bézout's identity 很容易测试它,为 ab 使用不同的值,并验证它是否像宣传的那样工作:

(define (test a b)
  (let* ((ans (extended-gcd a b))
         (x (car ans))
         (y (cdr ans)))
    (= (gcd a b) (+ (* a x) (* b y)))))

(test 384 256)
=> #t

请注意算法计算了其他值,通过更改您返回的内容您还可以获得以下内容:

Bézout coefficients:     old_s, old_t
Greatest common divisor: old_r
Quotients by the gcd:    t, s

关于algorithm - 如何实现扩展欧几里得算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728246/

相关文章:

python - 使用堆的中值维护

bash - Linux shell 脚本: Is it possible to modify the variable sent as parameter to a function?

javascript - 我可以将数据导出到另一个 React 组件吗?

if-statement - 方案( Racket )如果在 cond 内不返回任何内容

functional-programming - 如何加载库以支持 R5RS 语言(DrScheme)中的哈希表?

algorithm - 在字符串中实现数字乘法的最快方法(1000000 位)

Python 摩尔斯电码 : S. O.S

algorithm - 如何制作木炭绘图过滤器

scheme - Racket - 最简洁的列表理解方式?

sql - 以 'select statement' 格式从函数返回结果