简体   繁体   English

素数查找器-优化

[英]Prime number finder - optimization

I'm trying to build a prime number finder that would work as fast as possible. 我正在尝试构建一个质数查找器,该查找器将尽快运行。 This is the def function that is included in the program. 这是程序中包含的def函数。 I'm having problems with just one detail, which I have put in {brackets} below. 我仅在一个细节上遇到了问题,我在下面的{括号}中输入了这些细节。 I have also explained the main parameters. 我还解释了主要参数。

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

This function doesn't work properly. 此功能无法正常工作。 If instead of floored squared root of my number I just replace it with x/3 it will work just fine. 如果我用数字x / 3代替我数字的平方根而不是平方根,它将很好用。 But the problem is that I don't want to check all the possible dividers in between x**(1/2) and x/3, because it will only slow the function, nothing else. 但是问题是我不想检查x **(1/2)和x / 3之间的所有可能的分频器,因为它只会减慢函数的速度,而不会降低速度。 So here is the code that works: 所以这是起作用的代码:

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

If anyone sees the problem, help please :D 如果有人发现问题,请帮助:D

As pointed out in the comment above, python2 performs integer division so 1/2 == 0 正如上面的评论中指出的那样,python2执行整数除法,因此1/2 == 0

  • You can write your root as: 您可以将根写为:

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

     math.sqrt(x) 

The naive primality test can be implemented like this: 天真素性测试可以这样实现:

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