簡體   English   中英

優化第n個素數Ruby / Python的代碼

[英]Optimize code for nth prime number Ruby/Python

我需要以最快的方式在Ruby或Python中找到第n個質數:

require "prime"

puts Prime.first(n).join("")  

對於> = 100000的數字,這會花費很多時間。

如何優化此代碼?

嘗試一下:-

# Steps
    # List first 'n' prime
    # Choose the very last one


require "prime"

def nprime(n)
   (Prime.first n).last
end

puts nprime(10001)

它給了我迅速的答案:

$ ruby nprime.rb
   104743

您可以在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]

最初為低質數建立字典,以加快高質數。 查找第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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM