Advertisement
Guest User

project euler7 problem

a guest
Oct 25th, 2016
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scheme 1.29 KB | None | 0 0
  1. ;; Try the number against a list of all the previous primes
  2. ;; slow :(
  3.  
  4. (define primes (list 11 13 17 19 23 29)) ; the not-loop-unrolled primes
  5. (define count (+ 4 (length primes)))
  6.  
  7. (define (is-prime? candidate)
  8.   (define max (sqrt candidate))
  9.   (define (loop-through pr)
  10.     (cond
  11.      [(> (car pr) max) #t]
  12.      [(= 0 (remainder candidate (car pr))) #f]
  13.      [else (loop-through (cdr pr))]))
  14.   ;; first do some "loop unrolling"
  15.   (cond
  16.    [(= 0 (remainder candidate 3)) #f]
  17.    [(= 0 (remainder candidate 5)) #f]
  18.    [(= 0 (remainder candidate 7)) #f]
  19.    [else (loop-through primes)]))
  20.  
  21.  
  22. (define (get-10001st-prime)
  23.   (let loop ([n 31])
  24.     (cond
  25.      [(is-prime? n)
  26.       (if (= count 10001)
  27.           n
  28.           (begin
  29.             (append! primes (list n))
  30.             (set! count (+ 1 count))
  31.             (loop (+ n 2))))]
  32.      [else (loop (+ n 2))])))
  33.  
  34.  
  35. ; While this is a lot faster
  36.  
  37. (define (is-prime2? candidate)
  38.   (define max (sqrt candidate))
  39.   (let loop ([n 3])
  40.     (cond
  41.      [(> n max) #t]
  42.      [(= 0 (remainder candidate n)) #f]
  43.      [else (loop (+ n 2))])))
  44.  
  45. (define (get-10001st-prime2)
  46.   (let loop ([i 5]
  47.              [c 2])
  48.     (if (is-prime2? i)
  49.         (if (= c 10001)
  50.             i
  51.             (loop (+ i 2) (+ c 1)))
  52.         (loop (+ i 2) c))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement