【问题标题】:Is this code for Miller-Rabin test wrong? (answer for the exercise for 1.28 in SICP)这个 Miller-Rabin 测试的代码错了吗? (SICP 1.28 习题答案)
【发布时间】:2019-03-27 06:26:03
【问题描述】:

我试图在SICP中解决练习1.28,关于Miller-Rabin算法,之后我在网上找到了答案,但我认为答案是错误的。我来问问有没有错。

他在执行 expmod 循环时检查 (remainder (square base) m)=1 是否。然而,在做循环时,base 和 m 会保持不变,这意味着他正在做同样的检查,这不是 Miller-Rabin 测试想要做的。

(define (expmod base exp m)
  (cond ((= exp 0)
         1)
        ((nontrivial-square-root? base m) 
         0)
        ((even? exp)
         (remainder (square (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m))))

(define (nontrivial-square-root? a n)
  (and (not (= a 1))
       (not (= a (- n 1)))
       (= 1 (remainder (square a) n))))

如果n=k*2^c,我想我们应该检查一下(remainder (a^(k*2*(c-1))) n)=1

【问题讨论】:

    标签: scheme sicp


    【解决方案1】:

    这就是它应该做的。过程expmod 应该计算一个数模另一个数的指数,这次唯一的区别是每次递归时都要检查一个非平凡的平方根。 m 将在expmod 过程中保持不变,而您编写的miller-rabin 过程将运行expmod,每次都带有随机数m

    编码愉快!

    顺便说一句,SICP 祝你好运!我现在正在练习 2.45,它变得更容易(尽管有一些非常抽象的概念)。

    【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 2016-03-19
      • 2019-09-21
      • 2018-07-02
      • 2013-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多