Check for a prime number using recursive helper function

前端 未结 2 1750
闹比i
闹比i 2021-01-22 12:36

I am trying to check if a number is prime using recursion. I was required to use a recursive helper function, but I am not sure how I should implement it.

I think I know

相关标签:
2条回答
  • 2021-01-22 12:48
    (define (isPrimeHelper x k)
      (if (= x k) #t
      (if (= (remainder x k) 0) #f
         (isPrimeHelper x (+ k 1)))))
    
    (define ( isPrime x )
      (cond
        (( = x 0 ) #f)
        (( = x 1 ) #f)
        (( = x 2 ) #t)
         ( else (isPrimeHelper x 2 ) )))
    

    I prefer this version.

    0 讨论(0)
  • 2021-01-22 13:07

    Using a helper simply means that you should split your program in smaller parts, and possibly encapsulate loops with extra parameters in separate procedures - and in Scheme loops are frequently implemented via recursive calls. One (naïve) way to implement the is_prime procedure would be:

    (define (is_prime n)
      (cond ((<= n 1) #f)
            ((= n 2) #t)
            ((= (modulo n 2) 0) #f)
            (else (check 3 n))))
    
    ; recursive helper
    (define (check i n)
      (cond ((> (* i i) n) #t)
            ((= (modulo n i) 0) #f)
            (else (check (+ i 2) n))))
    

    There are many ways to implement this procedure, and many possible optimizations; the above should be enough get you started.

    0 讨论(0)
提交回复
热议问题