使用嵌套 for 循环生成素数

Using nested for loops to generate primes

我创建了素性测试算法,但它不起作用。

本质上,这些是我的程序执行的步骤:

lower = int(input("Lower Bound: "))
upper = int(input("Upper Bound: "))

print ("Primes between " + str(lower) + " and " + str(upper) + ": ")

primes = []

for i in range (lower, upper): 
  for num in range (2, upper/2):
    if i % num == 0: 
      print (str(i-(lower-1)) + ". " + str(i) + " = No")
      break
  else: 
    primes.append(i)

print(primes)

但是,不管一个数是不是素数,函数总是输出no,但我不知道为什么!

已修复。首先,我做了 floor 除法 // 运算符,所以它 returns 是一个整数。另外,我提出了一个条件,即除数不能被自己除掉。因为否则 4 将是 4 的质数。

lower = int(input("Lower Bound: "))
upper = int(input("Upper Bound: "))

print ("Primes between " + str(lower) + " and " + str(upper) + ": ")

primes = []

for i in range (lower, upper):
  for num in range (2, upper//2):
    if i % num == 0 and num != i: # modification here
      print (str(i-(lower-1)) + ". " + str(i) + " = No")
      break
  else:
    primes.append(i)

print(primes)

Out[1]: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]