Prime number finder - optimization

后端 未结 1 559
醉梦人生
醉梦人生 2021-01-26 12:33

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 deta

相关标签:
1条回答
  • 2021-01-26 12:43

    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
    
    0 讨论(0)
提交回复
热议问题