python寻找素数_在python中寻找素数

本文介绍了一个用Python实现的高效素数检测程序。通过只检查特定形式的除数并利用素数特性,该程序能够有效地找出素数。作者提出了几个关于程序效率及改进空间的问题。

我知道python“慢得像脏东西”,但我想做一个快速而高效的程序来找到素数。这就是我所拥有的:num = 5 #Start at five, 2 and 3 are printed manually and 4 is a multiple of 2

print("2")

print("3")

def isPrime(n):

#It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.

i = 5

w = 2

while (i * i <= n): #You only need to check up too the square root of n

if (n % i == 0): #If n is divisable by i, it is not a prime

return False

i += w

w = 6 - w

return True #If it isn´t ruled out by now, it is a prime

while True:

if ((num % 2 != 0) and (num % 3 != 0)): #save time, only run the function of numbers that are not multiples of 2 or 3

if (isPrime(num) == True):

print(num) #print the now proved prime out to the screen

num += 2 #You only need to check odd numbers

现在我的问题是:

-这会打印出所有的质数吗?

-这会打印出不是素数的数字吗?

-有没有更有效的方法?

-这将发展到什么程度(python的限制),有什么方法可以提高上限吗?在

使用python 2.7.12

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值