【问题标题】:Checks the primality of consecutive odd integers in a specified range检查指定范围内连续奇数的素数
【发布时间】:2015-11-30 20:18:34
【问题描述】:

以下程序找到给定数字n 的最小整数除数(大于1)。它以一种简单的方式做到这一点,通过测试n 是否可以被以2 开头的连续整数整除。

n 是素数当且仅当n 是它自己的最小除数。

(define (square x) (* x x))

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

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

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

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

如何编写一个程序来检查指定范围内连续奇数的素数?

(define (search_for_primes from to)
   (cond ((> from to) false)
         ((prime? from) (display from))
         (else (search_for_primes (+ 1 from) to))))

我的解决方案只是将1 写入输出。

【问题讨论】:

标签: algorithm scheme


【解决方案1】:

cond 将在 first 匹配处停止并仅执行相应的表达式。因此,如果您执行 (search_for_primes 1 xxx),1 会错误地被识别为素数,并且过程会停在那里。

你想要的是类似的东西

(define (search_for_primes from to)
  (unless (> from to)
    (when (prime? from)
      (display from)
      (display " "))
    (search_for_primes (+ 1 from) to)))

无论你是否找到素数,递归都在哪里完成。

测试:

> (search_for_primes 2 100)
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

【讨论】:

  • 我需要为2 添加额外检查是吗?它不是素数
  • 2 是质数,但 1 不是。见en.wikipedia.org/wiki/Prime_number
  • 比如把prime?改成(define (prime? n) (and (> n 1) (= (smallest-divisor n) n)))
  • 如何使用你的程序找到大于 1000 的三个最小素数?
  • 向过程添加参数并在递归调用期间在找到素数时减少它。
【解决方案2】:

您绝对应该从在该范围内进行高效筛(如 Eratosthenes 筛)开始,以有效捕获多个小素数。如果您的数字很小,那么做到sqrt(n) 就足够了。 (这对于例如 Project Euler 问题来说已经足够了。)

如果您的范围很小而数字很大,则使用它来获得“可能的素数”,然后对每个都使用您最喜欢的素数测试(有关某些选项,请参阅 https://en.wikipedia.org/wiki/Primality_test)。

如果你的范围很大并且你的数字很大......你就会遇到问题。 :-)

【讨论】:

  • 好的,假设我的函数 prime? 工作 log(n) 时间。如何解决我的问题?
猜你喜欢
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2020-10-03
相关资源
最近更新 更多