Prime number calculation fun

前端 未结 18 1791
深忆病人
深忆病人 2020-12-05 15:32

We\'re having a bit of fun here at work. It all started with one of the guys setting up a Hackintosh and we were wondering whether it was faster than a Windows Box of (nearl

18条回答
  •  情深已故
    2020-12-05 15:37

    It takes us under a second (2.4GHz) to generate the first 150000 prime numbers in Python using Sieve of Eratosthenes:

    #!/usr/bin/env python
    def iprimes_upto(limit):
        """Generate all prime numbers less then limit.
    
        http://stackoverflow.com/questions/188425/project-euler-problem#193605
        """
        is_prime = [True] * limit
        for n in range(2, limit):
            if is_prime[n]:
               yield n
               for i in range(n*n, limit, n): # start at ``n`` squared
                   is_prime[i] = False
    
    def sup_prime(n):
        """Return an integer upper bound for p(n).
    
           p(n) < n (log n + log log n - 1 + 1.8 log log n / log n)
    
           where p(n) is the n-th prime. 
           http://primes.utm.edu/howmany.shtml#2
        """
        from math import ceil, log
        assert n >= 13
        pn = n * (log(n) + log(log(n)) - 1 + 1.8 * log(log(n)) / log(n))
        return int(ceil(pn))
    
    if __name__ == '__main__':
        import sys
        max_number_of_primes = int(sys.argv[1]) if len(sys.argv) == 2 else 150000
        primes = list(iprimes_upto(sup_prime(max_number_of_primes)))
        print("Generated %d primes" % len(primes))
        n = 100
        print("The first %d primes are %s" % (n, primes[:n]))
    

    Example:

    $ python primes.py
    
    Generated 153465 primes
    The first 100 primes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 
    43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 
    127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
    199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
    283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
    383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
    467, 479, 487, 491, 499, 503, 509, 521, 523, 541]
    

提交回复
热议问题