Check for a prime number using recursive helper function

好久不见. 提交于 2019-12-20 02:56:14

问题


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 the algorithm, but I've never tried to use a recursive helper function in Racket. This is my current thoughts:

  1. See if n is divisible by i = 2
  2. Set i = i + 1
  3. If i^2 <= n continue.
  4. If no values of i evenly divided n, then it must be prime.

This is what I have so far...

(define (is_prime n)
  (if (<= n 1)
      #f
      (if (= (modulo n 2) 0)
          #f

)

What would be a good approach using a recursive helper function??

Thanks!


回答1:


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.




回答2:


(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.



来源:https://stackoverflow.com/questions/54258347/check-for-a-prime-number-using-recursive-helper-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!