Skip to content Skip to sidebar Skip to footer

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, w

Solution 1:

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

Post a Comment for "Prime Number Finder - Optimization"