in Programming

Project Euler Problem 7 Solution: Clojure

Problem Description, from Project Euler

What is the n-th prime number?

Problem Solution

This was simple to solve using the Sieve created for the solution to problem #3. To make the program variable, we start with finding all primes less than 1000. If that is not enough to solve the problem, we double this “maximum” value, and search for all primes less than 2000. Rinse, repeat.

The old stuff:

The new stuff:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(defn problem07 [nth]
    (defn try-find-nth-prime [primes max-number]
        (if (< (count primes) nth)
            ; if the list of primes is not long enough,
            ; double the maximum search number
            (try-find-nth-prime
                (sieve-of-eratosthenes (* max-number 2))
                (* max-number 2)
                )
            ; otherwise, take the nth member of the list
            (last (take nth primes))
            )
 
    )
(try-find-nth-prime (sieve-of-eratosthenes 1000) 1000)
)

  1. Hi Matt, I definitely see what you mean. Thanks for linking to an awesome post. I will try to follow these conventions in new posts!

Comments are closed.

  • Readers who shared this
  • wifi tv
  • Thank you!