你需要检查从2到n-1的所有数字(实际上是sqrt(n),但好吧,让它为n).
如果n可被任何数字整除,则它不是素数.如果数字是素数,则打印它.
for num in range(2,101):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print num
你可以写更短更pythonic:
for num in range(2,101):
if all(num%i!=0 for i in range(2,num)):
print num
正如我已经说过的,最好检查除数不是从2到n-1,而是从2到sqrt(n):
import math
for num in range(2,101):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print num
对于像101这样的小数字并不重要,但对于10 ** 8,差异将非常大.
您可以通过将检查范围增加2来进一步改善它,从而只检查奇数.像这样:
import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print num
编辑:
As in the first loop odd numbers are selected, in the second loop no
need to check with even numbers, so ‘i’ value can be start with 3 and
skipped by 2.
import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(3,int(math.sqrt(num))+1, 2)):
print num