如需转载请注明出处
闲着无聊,用学到的一些python基础皮毛写一点东西。用程序搜寻过一百万的素数,结果这段程序跑了45分钟,和峰哥说了下,都很感叹python的效率真是感人。
这里贴出程序全部代码。另外,如果真想找素数,可以参加寻找梅森素数的项目。这个就是闹着玩的了,欢迎留言。
import time
'''
1 candidate 候选规则 去掉 2、3、5、7、11、13、17
2 范围内的数字先进行筛选,初步符合的放到seed_c里面
'''
seeds = [3, 5, 7]
def find_the_prime_number(intmax):
"""
从候选名单中剔除符合2因子的数
:type range: object
"""
start = time.perf_counter()
candidates = list(range(11, intmax+1, 2))
isprime = True
for candidate in candidates:
for seed in seeds:
if (candidate % seed == 0) and (candidate in seeds):
'''
如果能被seed整除,同时也在素数记录中,说明是旧素数
弹出说明,退出循环
'''
print(str(candidate) + ' 是素数')
isprime = True
break
elif (candidate % seed == 0) and (candidate not in seeds) :
'''
如果不是旧有列表,也能被整除,说明不是素数
退出循环
'''
print(str(candidate) + '被' + str(seed) + '验证不是素数')
isprime = False
break
elif (candidate % seed != 0):
isprime = True
continue
if (candidate not in seeds) and (isprime == True):
'''
如果不能被现有列表的素数整除、又不在原来列表中,说明是新素数
添加到素数列表中
之前判断是素数
'''
print(str(candidate) + '是素数')
maxseed = max(seeds)
if candidate > max(seeds):
seeds.append(candidate)
# print(str(candidate) + '是新找到的素数')
# 列出素数
seeds.insert(0, 2)
print(seeds)
end = time.perf_counter()
print("运算时间是 ", end - start)
print('总数量是 '+ str(len(seeds)))
maxnum = input('输入范围: ')
intmax = int(maxnum)
find_the_prime_number(intmax)
# print('范围(20以上): ' + str(range))
# print(maxnum+"内,非第一次筛选的候选数有:" + str(find_the_prime_number(intmax)))