solution.scm 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. ;; https://projecteuler.net/problem=7
  2. ;; Find n-th prime number
  3. ;; Problem 7
  4. ;; By listing the first six prime numbers: 2, 3, 5, 7, 11,
  5. ;; and 13, we can see that the 6th prime is 13.
  6. ;; What is the 10 001st prime number?
  7. (import
  8. (except (rnrs base) let-values)
  9. (only (guile) lambda* λ))
  10. (define calc-check-limit
  11. (λ (n)
  12. "Calculate the number up to which one needs to check for
  13. factors."
  14. (inexact->exact (floor (sqrt n)))))
  15. (define too-high?
  16. (λ (num limit)
  17. "Check, whether the number is above the limit."
  18. (> num limit)))
  19. (define prime?
  20. (λ (num)
  21. "Check, whether the given number NUM is a prime number."
  22. (let ([limit (calc-check-limit num)])
  23. (let loop ([test-num 2])
  24. (cond
  25. [(too-high? test-num limit) #t]
  26. [else
  27. (cond
  28. [(= (remainder num test-num) 0) #f]
  29. [else
  30. (loop (+ test-num 1))])])))))
  31. (define next-num
  32. (λ (num)
  33. "Even numbers, except for 2, cannot be primes, so we add
  34. 2, to skip even numbers between odd numbers. This function
  35. assumes, that one gives it odd numbers as input."
  36. (+ num 2)))
  37. (define n-th-prime
  38. (λ (n)
  39. "Find the n-th prime number and return it."
  40. ;; Iterate through the numbers from 3 towards infinity,
  41. ;; until the n-th prime has been found.
  42. (let loop ([current-num 3] [found-primes 1])
  43. (let ([is-prime (prime? current-num)])
  44. (cond
  45. [(= found-primes (- n 1))
  46. (if is-prime
  47. current-num
  48. (loop (next-num current-num) found-primes))]
  49. [else
  50. (if is-prime
  51. (loop (next-num current-num) (+ found-primes 1))
  52. (loop (next-num current-num) found-primes))])))))
  53. (simple-format
  54. (current-output-port)
  55. "~a\n"
  56. (n-th-prime 10001)) ; 104743