project_euler/7.rb
Code:
# Project Euler Problem 7: 10001st Prime
# https://projecteuler.net/problem=7
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
# we can see that the 6th prime is 13.
# What is the 10,001st prime number?
def sieve(max)
primes = (0..max).to_a
primes[0] = primes[1] = nil
counter = 0
primes.each do |prime|
next unless prime
break if prime ** 2 > max
counter += 1
(prime ** 2).step(max, prime) { |m| primes[m] = nil }
end
return primes.compact
end
def solve(n)
return sieve(2 * n * Math.log(n))[n]
end
puts solve(6)
puts solve(10_001)
Output:
17
104759