題目:求指定範圍之內的質數。
(指在大於1的自然數中,除了1和它本身以外不再有其他因數的自然數)
代碼:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
lowernum = int(input('請輸入下限值:'))
uppernum = int(input('請輸入上限值:'))
if(lowernum > uppernum):
print('輸入錯誤:下限值大於上限值')
for i in range(lowernum,uppernum+1):
#小於1時,忽略
if( i <= 1 ):
pass
#大於1時,判定是否有其他因數
isPrime = True
for j in range(2,i): #在2~i-1 裏面判定是否存在其他因數
if( i % j == 0):
isPrime = False #存在其他因數
break
if(isPrime):
print(i)
執行結果:
請輸入下限值:3
請輸入上限值:89
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89