Python implements to judge whether a number with a large number of digits is prime.

I want to judge whether 1 million random numbers between [500000000, math.pow (2,63)-2] are prime numbers. When I use the following writing method, the program will not run all of a sudden. What is the problem and where can my algorithm be improved

def main():

    for k in range(1000000):
        num = random.randint(5000000000, math.pow(2, 63) - 2)
        -sharp  1
        if num > 1:
            -sharp 
            for i in range(2, num):
                if (num % i) == 0:
                    print(num, "")
                    break
            else:
                print(num, "")

        -sharp  1
        else:
            print(num, "")
Nov.15,2021

https://vv13.cn/posts/algorit.


slightly improved version, saving a large prime table may speed up filtering

import random
import math

def main():

    for k in range(50):
        num = random.randint(5000000000, math.pow(2, 63) - 2)
        -sharp  1
        -sharp 
        for i in range(2, int(math.sqrt(num))):
           if (num % i) == 0:
              print(num, "")
              break
                
        print(num, "")


main()

Prime sieve

install: pip install primesieve

 

for prime testing, there are no more than two approaches: deterministic testing and random testing.

deterministic testing can give deterministic results, but the speed will be slow. For example, the trial division you use and other optimized trial division and screening methods given by the answers. The trial division method is more suitable to determine the primality of a number, while the screening method is more suitable to determine the primality of a given range of numbers.

and the randomness test can not completely determine the primality of the number you want to judge, but how likely it is to be a prime, but its speed is faster. You can learn about the Fermat Sex Test and Rabin Miller Sex Test. This method is suitable for determining the primality of a large number .

< hr >

for your question, 1 million numbers between [50,000,000, math.pow (2,63)-2], trial division can be a waste of time. The best solution is to use the screening method to filter out all the primes below math.pow (2,63)-2 and save them, and then make a judgment. The other answers are almost done, so I won't repeat them.

Menu