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 10001st prime number?
Solution
#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 10001st prime number?
primes = [2,3]
while primes.length < 10001 do
candidate = primes[primes.length – 1] + 2;
isPrime = false
while !isPrime do
isPrime = true
for prime in primes
if candidate % prime == 0 then
isPrime = false
break
end
end
if !isPrime then
candidate += 2
else
primes.push(candidate)
end
end
end
puts primes[primes.length–1]
Discussion
This is pretty much a straight port of the C# solution. It turns out to be about an order of magnitude slower than the C# version (IronRuby ~11 seconds, C# ~ 1 second). It still comes up with the correct answer, and it’s well within the 1 minute rule.
If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).
Leave a Reply