Quickly determine if a number is prime in Python for numbers < 1 billion

后端 未结 5 2300
梦毁少年i
梦毁少年i 2021-02-20 11:06

My current algorithm to check the primality of numbers in python is way to slow for numbers between 10 million and 1 billion. I want it to be improved knowing that I will never

相关标签:
5条回答
  • 2021-02-20 11:12

    For numbers as large as 10^9, one approach can be to generate all primes up to sqrt(10^9) and then simply check the divisibility of the input number against the numbers in that list. If a number isn't divisible by any other prime less than or equal to its square root, it must itself be a prime (it must have at least one factor <=sqrt and another >= sqrt to not be prime). Notice how you do not need to test divisibility for all numbers, just up to the square root (which is around 32,000 - quite manageable I think). You can generate the list of primes using a sieve.

    You could also go for a probabilistic prime test. But they can be harder to understand, and for this problem simply using a generated list of primes should suffice.

    0 讨论(0)
  • 2021-02-20 11:16

    Well, I have a follow-up to my comment under (very good) Peter Van Der Heijden's answer about there being nothing good for really large primes (numbers in general) in the "popular" Python libraries. Turns out I was wrong - there is one in sympy (great library for symbolic algebra, among others):

    https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime

    Of course, it may yield false positives above 10**16, but this is already much better than anything else I could get doing nothing (except maybe pip install sympy ;) )

    0 讨论(0)
  • 2021-02-20 11:17
    def isprime(num):
    if (num==3)or(num==2):
        return(True)
    elif (num%2 == 0)or(num%5 == 0):
        return (False)
    elif ((((num+1)%6 ==0) or ((num-1)%6 ==0)) and (num>1)):
        return (True)
    else:
        return (False)
    

    I think this code is the fastest ..

    0 讨论(0)
  • 2021-02-20 11:27

    For solving Project Euler problems I did what you suggest in your question: Implement the Miller Rabin test (in C# but I suspect it will be fast in Python too). The algorithm is not that difficult. For numbers below 4,759,123,141 it is enough to check that a number is a strong pseudo prime to the bases 2, 7, 61. Combine that with trial division by small primes.

    I do not know how many of the problems you have solved so far, but having a fast primality test at your disposal will be of great value for a lot of the problems.

    0 讨论(0)
  • 2021-02-20 11:35

    You can first divide your n only by your primes_under_100.

    Also, precompute more primes.

    Also, you're actually store your range() result in memory - use irange() instead and use this memory for running Sieve of Eratosthenes algorithm.

    0 讨论(0)
提交回复
热议问题