[英]Optimize code for nth prime number Ruby/Python
I need to find the nth prime number, in the fastest way possible in Ruby or Python: 我需要以最快的方式在Ruby或Python中找到第n个质数:
require "prime"
puts Prime.first(n).join("")
This takes a lot of time for numbers >= 100000. 对于> = 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. 您可以在python中尝试此动态程序,它会在素数字典(由程序本身动态构建)中查找,该字典最初是空的,并且随着找到更大的素数而变得更快。
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)
查找第10000个素数的示例,在运行模块时在python shell中执行以下操作:prime(1000)prime(5000)prime(10000)
require "prime"
Prime::EratosthenesSieve.instance.get_nth_prime(1000000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.