Finding the nth prime number using Python

前端 未结 4 1780
礼貌的吻别
礼貌的吻别 2020-12-16 08:21

When I run this code, even for just counting to the 10th prime number (instead of 1000) I get a skewed/jacked output--all \"not prime\" titles for my is_composite variable,

4条回答
  •  不知归路
    2020-12-16 09:13

    This code below generates a list of primes upto 1 million. Using that list, you can test for primes < 1 Trillion in a reasonably fast way. This runs in a pretty fast time for 10-12 digit primes.

    import math
    from itertools import islice
    # number of primes below the square root of x
    # works well when x is large (x > 20 and much larger)
    numchecks = lambda x: int((math.sqrt(x))/(math.log(math.sqrt(x)) - 1.084)) + 1
    
    primes = [2,3,5]
    primes = primes + [x for x in range(7, 48, 2) if all((x%y for y in islice( primes, 1, int(math.sqrt(x)) )))]
    primes = primes + [x for x in range(49, 2400, 2) if all((x%y for y in islice( primes, 1, numchecks(x) )))]
    primes = primes + [x for x in range(2401, 1000000, 2) if all((x%y for y in islice( primes, 1, numchecks(x) )))]
    

    You can increase the number of saved primes by extending the process above, but the program will take a long time (but one time only process).

    In your code, you can test if 'test_num' is prime using the following...

    test_num = 23527631
    if test_num<100:
        checks = int(math.sqrt(test_num))
    else:
        checks = numchecks(test_num)
    
    isPrime = all(test_num%x for x in islice(primes, 0, checks))
    print 'The number is', 'prime' if isPrime else 'not prime'
    print 'Tested in', checks, 'divisions'
    

提交回复
热议问题