10001st prime number

The first six prime numbers are 2, 3, 5, 7, 11, and 13. The 6th prime number is 13.
What is the 10001st prime number?

Pick the solution you think is better, and describe how it works, or explain how it can be improved.

Solution A
n = 3
primes = [2]
while primes.size < 10001 do
    max = Math.sqrt(n)
    for p in primes do
      if p > max
        primes << n
        print "#{primes.size}: #{n}\n"
        break
      end
      break if n % p == 0
    end
    n = n + 1
end
print primes[10000], "\n"
 
Solution B
arr=[]
(2..120000).each{|i|(2..Math.sqrt(i).floor).detect{|j|i%j==0} or arr<<i}
p arr[10000]
 
Log in to accept this challenge
Submitted by others
  • Solution A uses Sieve of Eratosthenes algorithm. It's not required to try every integers to test prime property.

  • B is done in the smarter way while A is more straight forward.

  • A divides the number by prime numbers, and B divides the number by all numbers from 2 to sqrt(i).floor. So, A should be faster.

  • Both start off with an array that gets filled upon each iteration wherein the number is checked for divisibility against the rest of the numbers in the range. The solution to the right is more concise.

  • I think B is the better solution due to its brevity and clarity.

    While the two solutions are variations of the same elements (for instance, a loop, Math.sqrt(), modulo, and array insertion), solution B gets at the essence of the problem far more effectively by onelining useful constructs like .each() and conditional execution via or.

  • Neither. Use a library.

    require 'prime'
    
    Prime.first(10001).last
    
  • use require 'prime'. but i like "b" better.

  • Solution b. Short and sweet.

  • a

  • Solution B is not sure if 10001st prime number is included