Python并行判断多个大整数是否为素数

2016-12-03 董付国 Python小屋 Python小屋

本文主要用到Python标准库concurrent.futures提供的并发执行功能,类似于进程池的用法,在多核或多CPU平台能够大幅度提高处理速度。

from concurrent.futures import ProcessPoolExecutor


PRIMES = [1099726899285419,112582705942171,

          112272535095293, 115280095190773,

          115797848077099, 9000099011]


def isPrime(n):

    if n%2 == 0:

        return False


    for i in range(3, int(n**0.5)+1, 2):

        if n%i == 0:

            return False

    return True


def main():

    with ProcessPoolExecutor() as executor:

        for number, prime in zip(PRIMES, executor.map(isPrime, PRIMES)):

            print('%d is prime: %s' % (number, prime))


if __name__ == '__main__':

    main()