简体   繁体   中英

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? (it is but it should not print it)

2%2==0 so it should skip it...

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

Others have noted the error in the range(start,end) code. 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).

#### 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, 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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