python-求素数个数

# 菜鸟出没
# 非战斗人员请撤离
# 时间:2022/3/28 17:13
import math
from multiprocessing import cpu_count
from multiprocessing import Pool
# 判断数字是否为质数


def isPrime(n):
    if n <= 1:
        return False
    for j in range(2, int(math.sqrt(n)) + 1):
        if n % j == 0:
            return False
    return True
# 计算给定区间含有多少个质数


def howMany(T):
    sum = 0
    for k in T:
        if isPrime(k):
            sum += 1
    return sum
# 对整个数字空间N进行分段CPU_COUNT


def separateNum(N, CPU_COUNT):
    list = [[i for i in range(j, j+int(N/CPU_COUNT))]for j in range(0, N, int(N/CPU_COUNT))]
    x = N%CPU_COUNT
    if x != 0:
        for k in range(int(N/CPU_COUNT)*CPU_COUNT+1,N+1):
            list[CPU_COUNT-1].append(k)
    return list


if __name__ == '__main__':
    N = int(input())
    # 多进程
    CPU_COUNT = cpu_count()  ##CPU内核数 本机为8
    pool = Pool(CPU_COUNT)
    sepList = separateNum(N, CPU_COUNT)
    result = []
    for i in range(CPU_COUNT):
        result.append(pool.apply_async(howMany, (sepList[i], )))
    pool.close()
    pool.join()
    ans = 0
    list = [res.get() for res in result]
    print(sum(list), end = '')

你可能感兴趣的:(python)