简体   繁体   English

Python Prime Number for-else范围

[英]Python Prime Number for-else range

lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
   if num > 1:
       for i in range(2,num):
           if (num % i) == 0:
               break
       else:
           print(num)

Why does this code print "2" as a prime number? 为什么此代码将“ 2”打印为质数? (it is but it should not print it) (是,但不应打印)

2%2==0 so it should skip it... 2%2 == 0,所以应该跳过它...

num为2时, range(2, num)为空,因此if (num % i) == 0:不执行检查,并执行else块。

Others have noted the error in the range(start,end) code. 其他人已经注意到range(start,end)代码中的错误。 Correcting that, your code for primes could be rewritten as: 更正这一点,您的质数代码可以重写为:

lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
   if num > 1:
       for i in range(2,max(num,3)):
           if (num % i) == 0:
               break
       else:
           print(num)

This isn't the fastest way to get primes mind you, each potential prime must be tested against EVERY smaller number as a possible divisor. 这不是让素数引起您注意的最快方法,每个可能的素数都必须针对每个较小的数进行除数测试。 It's much faster to instead count upwards and work out the multiples of smaller numbers. 取而代之的是向上计数并计算出较小数字的倍数要快得多。 That way we only need to do the maths once for each possible divisor. 这样,我们只需要对每个可能的除数进行一次数学运算即可。

For completeness, here is a program that can produce primes efficiently (uses the sieve of Eratosthenes method). 为了完整起见,这是一个可以有效产生素数的程序(使用Eratosthenes方法的筛子)。

#### INPUTS    
lower = int(input("from:"))
upper = int(input("to:"))

### Code
n = upper
prime_booleans = [True for i in range(n+1)] 
p = 2
while (p * p <= n): 

    # Is current number a prime, eliminate the numbers that are multiples of it 
    if (prime_booleans[p] == True): 
        for i in range(p * 2, n+1, p): 
            prime_booleans[i] = False
    p += 1

# Print all prime numbers 
for p in range(lower, n): 
    if prime_booleans[p]: 
        print p, 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM