赞
踩
def isPrime1(n):
for i in range(2,n):#对2到n取余
if n % i == 0:
return False
else:#注意缩进
return True
def isPrime2(n):
for i in range(2,n//2+1):#对2到n/2取余
if n % i == 0:
return False
else:
return True
def isPrime3(n):
for i in range(2,int(n**0.5)):#对2到根号n取余
if n % i == 0:
return False
else:
return True
N = 1000#求素数的范围
strPrime = ""
for j in range(2,N):
if isPrime1(j):#使用isPrime1() isPrime2 isPrime3() isPrime4()函数功能相同效率不同,可以引入time判断使用的时间
#涉及简单计时http://www.cnblogs.com/didiaoxiaoguai/p/6684094.html
strPrime = strPrime + str(j) + " "
print(strPrime)
#以下为另一写法
def isPrime4(n):
for i in range(3,int(n**0.5),2):#将步长设为2
if n % i == 0:
return False
else:
return True
N = 1000 #
strPrime = "2 "
for j in range(3,N,2):
if isPrime4(j):
strPrime = strPrime + str(j) + " "
print(strPrime)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。