I need to find the nth prime number, in the fastest way possible in Ruby or Python:
require "prime"
puts Prime.first(n).join("")
This takes a lot of time for numbers >= 100000.
How do I optimize this code?
I need to find the nth prime number, in the fastest way possible in Ruby or Python:
require "prime"
puts Prime.first(n).join("")
This takes a lot of time for numbers >= 100000.
How do I optimize this code?
Give this a try:-
# Steps
# List first 'n' prime
# Choose the very last one
require "prime"
def nprime(n)
(Prime.first n).last
end
puts nprime(10001)
It gave me the answer preety quick:
$ ruby nprime.rb
104743
You may try this dynamic program in python, this looks up in a dictionary of primes(built dynamically by the program itself), which is initially empty and it gets faster as you find larger primes.
dict = {}
def prime(x):
dict[1] = 2
s = x
if x in dict:
return dict[s]
else:
while s > 0:
if s in dict:
pno = int(dict[s]) + 1
break
s-=1
while s < x:
m = 1
while m <= s:
if pno % dict[m] == 0:
pno+=1
m=1
else:
m+=1
dict[s+1]= pno
s+=1
return dict[x]
initially build the dictionary for lower primes for speeding up higher ones. Example to find the 10000th prime, do the following in python shell ahen running the module: prime(1000) prime(5000) prime(10000)