# 找出所有素数（Python版）

2016年11月14日 / 63次阅读
Python

• 打开支付宝，搜索“ 529018372 ”，领取专属红包！每日支付每日领。

``````def PrimeNumber(EndNum=100, StartNum=2):
# you can only leave the StartNum be default or both while calling
""" Display prime number sequence
Positive integer argument ONLY.
Please do not make the difference between StartNum and EndNum too big.
PrimeNumber() means default argument value from 2 to 100.
PrimeNumber(500) means display all prime number from 2 to 500.
PrimeNumber(500, 300) means display all prime number from 300 to 500.
"""
#input type and validation check
if type(StartNum) is not int:
return
if type(EndNum) is not int:
return
if (StartNum < 0) or (EndNum < 0):
return

if StartNum < 2:
StartNum = 2 # start point
if StartNum > EndNum:
return

total = 0
print('Calculating...hope the number is not very big...')
for i in range(StartNum, EndNum+1):
for j in range(2, int(i/2)+1): #if int(i/2)+1<=2, it'll run into else clause directly; use int(i/2)+1 to make it faster.
if i%j == 0: # find a divisor
break; # not a prime number and else will not be executed
else: # after for loop is over except break
# total++ is not supported in Python
#total = total + 1
total += 1
print('  ',i)

print('Total:', total)
return

Ctrl+D 收藏本页