我写的一个求质数的函数:
>>> import math
>>> def getz(n):
iszhishu=True
testn=int(math.sqrt(n))+1
for nn in range(2,testn):
if n%nn==0:
iszhishu=False
print n,"is NOT a zhishu,yinzi is ",nn
break
if iszhishu:
print n,"IS a zhishu"
>>> for x in range(3,101):
getz(x)
基本的原理就是以前我们老师讲过的,看一个数是不是质数,将这个数开方,用比它的开方值小的数去除这个数,如果都除不断的话,就是质数。下面把getz(n)改了一下,我现在已经求得了10000以内的质数表,速度比较慢,出来的时候,像看动画一样。
>>> import math
>>> def getz(n):
iszhishu=True
testn=int(math.sqrt(n))+1
for nn in range(2,testn):
if n%nn==0:
iszhishu=False
#print n,"is NOT a zhishu,yinzi is ",nn
break
#if iszhishu:
# print n,"IS a zhishu"
return iszhishu
>>> for x in range(1,10000):
if getz(x):
print x,