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

后端 未结 5 2383
梦毁少年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条回答
  •  萌比男神i
    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.

提交回复
热议问题