我正在尝试在Scheme中为RSA实现编写扩展的Euclidian算法的代码。
关于我的问题的事情是,我无法编写一个递归算法,其中内部步骤的输出必须是连续外部步骤的输入。我希望它给出最外层步骤的结果,但是可以看出,它给出了最内层步骤的结果。我为此编写了一个程序(有点混乱,但是我找不到时间进行编辑。):
(define ax+by=1
(lambda (a b)
(define q (quotient a b))
(define r (remainder a b))
(define make-list (lambda (x y)
(list x y)))
(define solution-helper-x-prime (lambda (a b q r)
(if (= r 1) (- 0 q) (solution-helper-x-prime b r (quotient b r) (remainder b r)))
))
(define solution-helper-y-prime (lambda (a b q r)
(if (= r 1) (- r (* q (- 0 q) )) (solution-helper-y-prime b r (quotient b r) (remainder b r))
))
(define solution-first-step (lambda (a b q r)
(if (= r 1) (make-list r (- 0 q))
(make-list (solution-helper-x-prime b r (quotient b r) (remainder b r)) (solution-helper-y-prime b r (quotient b r) (remainder b r))))
))
(display (solution-first-step a b q r))
))
所有帮助和建议将不胜感激。 (P.S.我添加了一份给我们的说明的摘要,但看不到图片。如果有问题,请告诉我。)
答案 0 :(得分:3)
这是一个Diophantine方程,很难解决。我想出了一个适用于this explanation的迭代解决方案,但是不得不将问题分成几部分-首先,通过应用extended Euclidean algorithm获得商列表:
(define (quotients a b)
(let loop ([a a] [b b] [lst '()])
(if (<= b 1)
lst
(loop b (remainder a b) (cons (quotient a b) lst)))))
第二,返回并求解方程:
(define (solve x y lst)
(if (null? lst)
(list x y)
(solve y (+ x (* (car lst) y)) (cdr lst))))
最后,将它们放在一起并确定解决方案的正确迹象:
(define (ax+by=1 a b)
(let* ([ans (solve 0 1 (quotients a b))]
[x (car ans)]
[y (cadr ans)])
(cond ((and (= a 0) (= b 1))
(list 0 1))
((and (= a 1) (= b 0))
(list 1 0))
((= (+ (* a (- x)) (* b y)) 1)
(list (- x) y))
((= (+ (* a x) (* b (- y))) 1)
(list x (- y)))
(else (error "Equation has no solution")))))
例如:
(ax+by=1 1027 712)
=> '(-165 238)
(ax+by=1 91 72)
=> '(19 -24)
(ax+by=1 13 13)
=> Equation has no solution