目录
正在加载目录…
正在阅读专栏 SICP:Structure and Interpretation of Computer Programs 第 14 篇 · 共 80 篇 · 18%

SICP:1.2.6 Example: Testing for Primality

发布于 2026-09-18 08:12 · 最后编辑于 2026-09-18 08:48 · 版本 v2 · 字数 7,663 · 预计阅读 16 分钟 👁 14 次阅读

SICP:1.2.6 Example: Testing for Primality

本文逐段翻译 SICP 第二版 §1.2.6《Example: Testing for Primality》,保留 divisor search、Fermat test、probabilistic methods、Scheme code、复杂度符号以及 Exercises 1.21–1.28 的原文顺序。

TL;DR

  • 本节介绍两种 primality testing methods:通过搜索 divisors 的 Θ(√n) 方法,以及基于 Fermat's Little Theorem、具有 Θ(log n) growth 的 probabilistic method。
  • Fermat test 随机选择 a,检查 aⁿ mod n 是否等于 a;失败可以确定 composite,反复通过只能提高 confidence。
  • Carmichael numbers 能 fool Fermat test;Miller–Rabin test 通过检测 nontrivial square roots of 1 避免这一问题。

目录

章节说明
1.2.6 Example: Testing for Primality两种 primality-testing methods
Searching for divisorssmallest-divisor 与 prime?
The Fermat testFermat's Little Theorem 与 expmod
Probabilistic methodserror probability、Carmichael 与 Miller–Rabin
Exercises 1.21–1.28primality-testing programming projects

1.2.6 Example: Testing for Primality

本节描述两种检查 integer n 是否 prime 的 methods:一种 order of growth 为 book Z G D 3(book Z G D 13n),另一种“probabilistic” algorithm 的 order of growth 为 book Z G D 3(log n)。本节结尾的 exercises 提出了基于这些 algorithms 的 programming projects。

Searching for divisors

自 ancient times 以来,mathematicians 就一直对 prime numbers 相关的问题着迷,许多人都研究过如何 test 一个 number 是否 prime。一种方式是寻找 number 的 divisors。下面的 program 寻找给定 number n 的 smallest integral divisor(大于 1)。它从 2 开始,用 successive integers straightforward 地测试 n 的 divisibility:

scheme
(define (smallest-divisor n)
  (find-divisor n 2))

(define (find-divisor n test-divisor)
  (cond ((> (square test-divisor) n) n)
        ((divides? test-divisor n) test-divisor)
        (else (find-divisor n (+ test-divisor 1)))))

(define (divides? a b)
  (= (remainder b a) 0))

可以如下 test 一个 number 是否 prime:当且仅当 n 是它自己的 smallest divisor 时,n 才是 prime。

scheme
(define (prime? n)
  (= n (smallest-divisor n)))

find-divisor 的 end test 建立在以下 fact 之上:如果 n 不是 prime,它一定拥有一个小于或等于 book Z G D 13n 的 divisor1。这意味着 algorithm 只需测试 1 与 book Z G D 13n 之间的 divisors。因此,识别 n 为 prime 所需 steps 的 order of growth 是 book Z G D 3(book Z G D 13n)。

The Fermat test

Θ(log n) 的 primality test 建立在 number theory 中称为 Fermat's Little Theorem 的 result 之上2。

Fermat's Little Theorem: 如果 n 是 prime number,a 是小于 n 的任意 positive integer,那么 a 的 nth power 与 a modulo n congruent。

(如果两个 numbers 除以 n 后拥有相同的 remainder,就说它们 congruent modulo n。number a 除以 n 后的 remainder,也称为 a 的 remainder modulo n,或简称 a modulo n。)

如果 n 不是 prime,那么一般而言,大多数小于 n 的 numbers a 都不会满足上述 relation。这就得到以下 algorithm:给定 number n,随机选择一个 a < n,计算 aⁿ modulo n 的 remainder。如果 result 不等于 a,就可以确定 n 不是 prime;如果 result 等于 a,则 n 很可能是 prime。再选择另一个 random a,使用相同 method test。如果它也满足 equation,就能更加 confident 地认为 n 是 prime。尝试越来越多的 a values,可以不断增加 confidence。这个 algorithm 称为 Fermat test。

要实现 Fermat test,需要一个计算某个 number modulo 另一个 number 的 exponential 的 procedure:

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

这与 §1.2.4 的 fast-expt procedure 非常 similar。它使用 successive squaring,因此 steps 数量随 exponent logarithmically growth3。

Fermat test 随机选择一个介于 1 和 n - 1(inclusive)之间的 number a,检查 a 的 nth power modulo n 的 remainder 是否等于 a。随机 number a 使用 procedure random 选择;假设 random 作为 primitive 包含在 Scheme 中。random 返回一个小于其 integer input 的 nonnegative integer。因此,要取得 1 到 n - 1 之间的 random number,可以把 n - 1 作为 input 传给 random,再给 result 加 1:

scheme
(define (fermat-test n)
  (define (try-it a)
    (= (expmod a n n) a))
  (try-it (+ 1 (random (- n 1)))))

下面的 procedure 按 parameter 指定的次数运行 test。如果 test 每次都 succeeds,它的 value 是 true;否则是 false:

scheme
(define (fast-prime? n times)
  (cond ((= times 0) true)
        ((fermat-test n) (fast-prime? n (- times 1)))
        (else false)))

Probabilistic methods

Fermat test 的 character 与大多数 familiar algorithms 不同;后者计算 guaranteed correct 的 answer,而 Fermat test 得到的 answer 只有 probable correctness。更 precisely 地说,如果 n 在某次 Fermat test 中 fails,我们可以确定 n 不是 prime。但 n 通过 test 虽然是 extremely strong indication,却仍不能 guarantee n 是 prime。我们希望能够说:对于任何 n,只要执行足够多次 test,并发现 n 始终通过,就可以把 primality test 的 probability of error 降到任意小。

不幸的是,这个 assertion 并不 quite correct。确实存在能够 fool Fermat test 的 numbers:它们不是 prime,却对所有 a < n 都满足 aⁿ 与 a modulo n congruent。这类 numbers extremely rare,因此 Fermat test 在 practice 中相当 reliable4。

存在不会被 fooled 的 Fermat-test variations。这些 tests 和 Fermat method 一样,通过随机选择 a < n 并检查依赖于 n 与 a 的 condition 来 test integer n 的 primality。不同的是,可以证明:对于任意 n,除非 n 是 prime,否则大多数 a < n 都不会满足该 condition(Exercise 1.28 是一个 example)。因此,如果 n 对某个 random a 通过 test,它是 prime 的 chances 大于一半;如果它对两个 random choices of a 都通过,成为 prime 的 chances 大于 3/4。使用越来越多的 randomly chosen a values 运行 test,就可以把 error probability 降到任意小。

这种能够证明 error chance 会 arbitrarily small 的 tests 的存在,引起了人们对这类 algorithms 的兴趣;它们被称为 probabilistic algorithms。这个领域有大量 research activity,probabilistic algorithms 也已经 fruitful 地应用于许多 fields5。

Exercises 1.21–1.28

Exercise 1.21

使用 smallest-divisor procedure,找出下列 numbers 各自的 smallest divisor:199、1999、19999。

Exercise 1.22

大多数 Lisp implementations 包含一个名为 runtime 的 primitive,它返回一个 integer,表示 system 已经运行的 time(例如以 microseconds 计)。下面的 timed-prime-test procedure 接受 integer n,打印 n 并检查它是否 prime。如果 n 是 prime,procedure 会打印三个 asterisks,随后打印执行 test 所用的 time:

scheme
(define (timed-prime-test n)
  (newline)
  (display n)
  (start-prime-test n (runtime)))

(define (start-prime-test n start-time)
  (if (prime? n)
      (report-prime (- (runtime) start-time))))

(define (report-prime elapsed-time)
  (display " *** ")
  (display elapsed-time))

使用这个 procedure,写一个 search-for-primes,检查指定 range 中 consecutive odd integers 的 primality。用它找出以下各组中最小的三个 primes:大于 1000、大于 10,000、大于 100,000、大于 1,000,000。记录 test 每个 prime 所需的 time。

由于 testing algorithm 的 order of growth 是 Θ(√n),应该预期 test 约 10,000 附近的 primes 所需 time,大约是 test 约 1000 附近 primes 的 √10 倍。你的 timing data 是否支持这一点?100,000 和 1,000,000 的 data 在多大程度上支持 √n prediction?你的 result 是否与“programs 在 machine 上的运行 time 与 computation 所需 steps 数量成 proportional”这一 notion compatible?

Exercise 1.23

本节开头的 smallest-divisor procedure 做了许多 needless testing:检查 number 是否 divisible by 2 后,就没有必要再检查任何更大的 even numbers。这提示 test-divisor 的 values 不应是 2, 3, 4, 5, 6, ...,而应是 2, 3, 5, 7, 9, ...。

定义 next procedure:当 input 等于 2 时返回 3,否则返回 input 加 2。修改 smallest-divisor,使用 (next test-divisor) 替换 (+ test-divisor 1)。让 timed-prime-test 使用这个 modified smallest-divisor,对 Exercise 1.22 找到的 12 个 primes 各运行 test。由于 modification 将 test steps 数量减半,应该预期运行速度约快两倍。这个 expectation 得到 confirmation 了吗?如果没有,两个 algorithms 的 observed speed ratio 是多少?如何解释它与 2 不同?

Exercise 1.24

修改 Exercise 1.22 的 timed-prime-test,使其使用 fast-prime?(Fermat method),并 test Exercise 1.22 找到的 12 个 primes。由于 Fermat test 的 growth 是 Θ(log n),预期 test 约 1,000,000 附近 primes 所需 time 与 test 约 1000 附近 primes 所需 time 有什么关系?你的 data 是否支持这一点?能否解释找到的 discrepancy?

Exercise 1.25

Alyssa P. Hacker 抱怨我们在写 expmod 时做了大量 extra work。她说,既然已经知道如何计算 exponentials,就可以简单写成:

scheme
(define (expmod base exp m)
  (remainder (fast-expt base exp) m))

她说得对吗?这个 procedure 能同样适用于 fast prime tester 吗?解释。

Exercise 1.26

Louis Reasoner 在完成 Exercise 1.24 时遇到很大困难。他的 fast-prime? test 似乎比 prime? test 运行更慢。检查 Louis 的 code 后发现,他将 expmod procedure 重写为显式 multiplication,而不是调用 square:

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

Louis 说:“我看不出这会有什么 difference。”Eva 回答:“我看得出。这样写,你把 Θ(log n) process transform 成了 Θ(n) process。”解释。

Exercise 1.27

证明 footnote 47 中列出的 Carmichael numbers 确实会 fool Fermat test。也就是说,写一个 procedure,接受 integer n,测试对于每个 a < n,aⁿ 是否 congruent to a modulo n,并用 footnote 中给出的 Carmichael numbers 运行你的 procedure。

Exercise 1.28

一种不会被 fooled 的 Fermat-test variant 称为 Miller–Rabin test(Miller 1976;Rabin 1980)。它从 Fermat's Little Theorem 的 alternate form 出发:如果 n 是 prime number,a 是小于 n 的任意 positive integer,那么 a 的 (n - 1)st power congruent to 1 modulo n。

要用 Miller–Rabin test 检查 n 的 primality,选择一个 random a < n,使用 expmod procedure 计算 a 的 (n - 1)st power modulo n。不过,每当 expmod 执行 squaring step 时,都要检查是否发现了“nontrivial square root of 1 modulo n”:即一个不等于 1 或 n - 1、但其 square 等于 1 modulo n 的 number。

可以证明,如果存在这样的 nontrivial square root of 1,那么 n 不是 prime。还可以证明,如果 n 是一个不是 prime 的 odd number,那么对于至少一半的 a < n,以这种方式计算 aⁿ⁻¹ 时都会发现 nontrivial square root of 1 modulo n。(这正是 Miller–Rabin test 不会被 fooled 的原因。)

修改 expmod,使其在发现 nontrivial square root of 1 时发出 signal;再用它实现一个 analogous to fermat-test 的 Miller–Rabin test。用 various known primes 和 non-primes test 你的 procedure。提示:一种 convenient 的 signal 方式,是让 expmod 返回 0。

图与格式复核

  • 本节没有独立 large figure;Θ、√n 与相关 mathematical symbols 使用原始 GIF,并保留原文位置。
  • smallest-divisor、prime?、expmod、fermat-test、fast-prime? 与 Exercises 1.21–1.28 的 code/题干顺序保持不变。
  • 原始图件尺寸:Θ 符号 9×10、square-root 符号 11×14、相关小数学符号 12×5 与 10×6。

术语对照

English译法/处理
primality testing保留 primality testing;必要处译作素性测试
divisor / divisibility保留 divisor、divisibility;必要处译作因数、整除性
Fermat's Little Theorem保留 Fermat's Little Theorem;必要处译作费马小定理
congruent modulo保留 congruent modulo;必要处译作模同余
probabilistic algorithm保留 probabilistic algorithm;必要处译作概率算法
Carmichael number保留 Carmichael number;必要处译作 Carmichael 数
Miller–Rabin test保留 Miller–Rabin test;必要处译作 Miller–Rabin 测试
nontrivial square root保留 nontrivial square root;必要处译作非平凡平方根

参考资料

  1. 如果 d 是 n 的 divisor,那么 n/d 也一定是 divisor;但 d 与 n/d 不可能同时大于 book Z G D 13n。 ↩

  2. Pierre de Fermat(1601–1665)被认为是 modern number theory 的 founder。Fermat's Little Theorem 出现在他 1640 年写的一封信中;Euler 于 1736 年给出了第一份 published proof。 ↩

  3. 当 exponent e > 1 时,reduction steps 建立在以下 fact 上:对任意 integers x、y 和 m,可以分别计算 x modulo m 与 y modulo m 的 remainders,将它们相乘,再取 result modulo m,从而得到 x 乘 y modulo m 的 remainder。这样可以避免处理远大于 m 的 numbers。 ↩

  4. 会 fool Fermat test 的 numbers 称为 Carmichael numbers。小于 100,000,000 的 Carmichael numbers 有 255 个;最小的几个是 561、1105、1729、2465、2821 和 6601。随机选择 very large numbers 做 primality testing 时,遇到 fool Fermat test 的 value 的 chance,小于 cosmic radiation 让 computer 在执行“correct” algorithm 时出错的 chance。 ↩

  5. Probabilistic prime testing 最 striking 的应用领域之一是 cryptography。虽然 factor arbitrary 200-digit number 在 computationally infeasible,但 Fermat test 可以在几 seconds 内检查这样一个 number 的 primality;这构成了 Rivest、Shamir 和 Adleman(1977)提出的构造“unbreakable codes”技术的 basis,即 widely used 的 RSA algorithm。 ↩

← 返回列表
← 上一篇 SICP:1.2.5 Greatest Common Divisors 下一篇 → SICP:1.3.1 Procedures as Arguments

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论