简体   繁体   English

方案递归函数

[英]Scheme Recursive Function

Can someone give me an explanation as to how the following function works recursively. 谁能给我一个关于以下函数如何递归工作的解释。 I can understand simpler recursive examples, but I don't understand how (smooth n (- k 1)) gives the value desired under the or statement here. 我可以理解更简单的递归示例,但是我不理解(smooth n (- k 1))如何在此处的or语句下提供所需的值。

(define (divides a b)
  (= (modulo b a) 0))

(define (smooth n k)
  (and (>= k 2)
       (or (divides k n)
           (smooth n (- k 1)))))

(define (isprime p)
  (if (< p 2)
      #f
      (not (smooth p (floor (sqrt p))))))

I wrote an isprime function that doesn't use 1 as a prime number, but I still don't quite understand how the above function works/how it works with this example. 我编写了一个isprime函数,该函数不使用1作为质数,但我仍然不太了解上述函数的工作方式/在本示例中如何使用。

Perhaps it'll be easier to understand if we rewrite smooth as follows - it's a completely equivalent form, but makes use of cond instead of and , or : 如果我们按以下方式重写smooth ,也许会更容易理解-它是完全等效的形式,但是使用cond代替and or

(define (smooth n k)
  (cond ((< k 2)
         #f)
        ((divides k n)
         #t)
        (else
         (smooth n (- k 1)))))

Basically, the procedure is stating that: 基本上,该过程表明:

  • if k is less than 2, then n is not "smooth" 如果k小于2,则n不“平滑”
  • if k divides exactly n , then n is "smooth" 如果k正好除以n ,则n为“平滑”
  • otherwise, subtract 1 from k and keep trying 否则,从k减去1并继续尝试

In other words: if n has any divisor besides itself and 1, we say it's "smooth". 换句话说:如果n除1和1外还有任何除数,我们说它是“平滑的”。 Clearly, it's easy to write a procedure that tests if a number is prime, in terms of its "smoothness" - a number is prime if it's greater than 2 and it's not smooth (meaning: it doesn't have a divisor besides itself and 1 ). 显然,编写一个测试数字是否为质数的过程很容易,就其“平滑度”而言,如果数字大于2并且不平滑,则它是质数(意思是:它本身没有除数,并且1 )。 And this post explains why we only have to test the divisors up to the square root of a number to determine if it's prime. 这篇文章解释了为什么我们只需要测试除数直到数字的平方根即可确定它是否为质数。

It is easier to understand if you try to write down each call. 如果您尝试记下每个呼叫,则更容易理解。 For example: 例如:

(smooth 5 4)
    (smooth 5 3)
        (smooth 5 2)


(define (smooth 5 3)
   (and (>= 4 2)
        (or (divides 3 5)
            (smooth 5 (- 3 1)))))

(define (smooth 5 2)
   (and (>= 2 2)
        (or (divides 2 5)
            (smooth 5 (- 2 1)))))

(define (smooth 5 1)
   (and (>= 2 1) # This returns false
        #t))

(define (smooth 5 2)
   (and #f #t))

(define (smooth 5 3)
   (and #t #f))

(define (smooth 5 4)
   (and #t #f))

#f

smooth nk is true if n has a divisor between 2 and k . 如果n的除数在2到k之间,则smooth nk为true。

It is just equivalent to a loop actually : 实际上,这等效于一个循环:

for i from k to 2 :
    if i divides n, return True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM