输出应如下:
给出数字范围的下限:0
给出数字范围的上限:1
0不能是素数。你知道吗
1不能是素数。你知道吗
在测试范围内找不到素数。你知道吗
给出数字范围的下限:0
给出数字范围的上限:20
0不能是素数。你知道吗
1不能是素数。你知道吗
2是素数。你知道吗
3是素数。你知道吗
4不是素数,因为2*2=4
5是素数。你知道吗
6不是素数,因为2*3=6
7是素数。你知道吗
8不是素数,因为2*4=8
9不是素数,因为3*3=9
10不是素数,因为2*5=10
11是素数。你知道吗
12不是素数,因为2*6=12
13是素数。你知道吗
14不是素数,因为2*7=14
15不是素数,因为3*5=15
16不是素数,因为2*8=16
17是质数。你知道吗
18不是素数,因为2*9=18
19是质数。你知道吗
20不是素数,因为2*10=20
搜索了21个数字,其中8个是素数。你知道吗
最后一次发现是19岁。你知道吗
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low,high):
if n<2:
print (n, "cannot be prime.")
for n in range(low,high):
for x in range (2, n):
if n % x == 0: # is n divisible with x? If yes, not a prime
y = n//x*x
print(n, "is not a prime, because", x, "*", n//x, "=", y)
break #this breaks the inner loop, and we continue with the outer!
else:
print(n, "is a prime.")
break
代码未成功运行 它显示输出:
给出数字范围的下限:0↩ 你知道吗
给出数字范围的上限:20↩ 你知道吗
0不能是素数。↩ 你知道吗
1不能是素数。↩ 你知道吗
3是素数。↩ 你知道吗
4不是素数,因为2*2=4↩ 你知道吗
5是素数。↩ 你知道吗
6不是素数,因为2*3=6↩ 你知道吗
7是素数。↩ 你知道吗
8不是素数,因为2*4=8↩ 你知道吗
9是素数。↩ 你知道吗
10不是素数,因为2*5=10↩ 你知道吗
11是素数。↩ 你知道吗
12不是素数,因为2*6=12↩ 你知道吗
13是素数。↩ 你知道吗
14不是素数,因为2*7=14↩ 你知道吗
15是素数。↩ 你知道吗
16不是素数,因为2*8=16↩ 你知道吗
17是质数。↩ 你知道吗
18不是素数,因为2*9=18↩ 你知道吗
19是质数。你知道吗
试着用这个在0-20范围内有效
您没有检查
n
是否可被2和n
之间的所有数字整除,因为在这两种情况下,您都会在第一次iteretion之后退出内部for循环(当n
可被x
整除时,以及当它不可整除时)。你知道吗要修复它,需要将
else
块移到外循环(因此它只在不退出循环时运行,这意味着n
是prime),并且只在n
不是prime时中断。你知道吗相关问题 更多 >
编程相关推荐