简体   繁体   中英

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. 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. 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. 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

As pointed out in the comment above, python2 performs integer division so 1/2 == 0

  • You can write your root as:

     x**0.5 
  • or using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM