簡體   English   中英

素數查找器-優化

[英]Prime number finder - optimization

我正在嘗試構建一個質數查找器,該查找器將盡快運行。 這是程序中包含的def函數。 我僅在一個細節上遇到了問題,我在下面的{括號}中輸入了這些細節。 我還解釋了主要參數。

import math
def is_prime(x):
    c=0      #a simple counter
    a=7      #a (+ k*6)a group of all possible deviders of the number(if 2,3 and 5 are taken away)
    b=11      #the other group
    {r=x**(1/2)}      #root of the number
    {f=math.floor(r)}       #floor of the root
    if x%2!=0 and x%3!=0 and x%5!=0:      #eliminate all multiples of 2,3 and 5
        while (c==0 and {a<f}):         #while loop
                if x%a==0 or x%b==0:
                        c+=1          #if true -> will break
                a+=6        #adding 6 to a and b (numbers that have a potential to devide
                b+=6
        if c==0:       #if a number not divisable by anything, return number
            return x

此功能無法正常工作。 如果我用數字x / 3代替我數字的平方根而不是平方根,它將很好用。 但是問題是我不想檢查x **(1/2)和x / 3之間的所有可能的分頻器,因為它只會減慢函數的速度,而不會降低速度。 所以這是起作用的代碼:

import math
def is_prime(x):
c=0
a=7
b=11
if x%2!=0 and x%3!=0 and x%5!=0:
        while (c==0 and a<x/3):
                if x%a==0 or x%b==0:
                        c+=1
                a+=6
                b+=6
        if c==0:
            return x

如果有人發現問題,請幫助:D

正如上面的評論中指出的那樣,python2執行整數除法,因此1/2 == 0

  • 您可以將根寫為:

     x**0.5 
  • 或使用math.sqrt:

     math.sqrt(x) 

天真素性測試可以這樣實現:

def is_prime(n):
    if n<=1: return False
    if n<=3: return True
    if not n%2 or not n%3: return False
    i=5
    while i*i<=n:
        if n%i==0: return False
        i+=2
        if n%i==0: return False
        i+=4
    return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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