Home > database >  Python prime number finder doesn't work (using break command)
Python prime number finder doesn't work (using break command)

Time:08-28

I'm trying to make a relatively efficient piece of Python code that will sum all the primes under 2 million, but this code doesn't seem to work. It regards numbers like 9 and 15 prime for some reason:

sum = 2

for num in range(3, 2000000, 2):
  for i in range(2, 1 int(num**0.5)):
    if num % i == 0:
      break
  sum  = num

print(sum)

CodePudding user response:

As written, your code ignores the checks in the inner for loop, and sums the current number regardless of whether or not it's a prime or not.

Either use a flag variable:

prime_sum = 2

for num in range(3, 2000000, 2):
  is_prime = True
  for i in range(2, 1 int(num**0.5)):
    if num % i == 0:
      is_prime = False
      break
  if is_prime:
    prime_sum  = num

print(prime_sum)

or use the for loop's else clause (which only runs after the loop runs to completion - ie. no break):

prime_sum = 2

for num in range(3, 2000000, 2):
  for i in range(2, 1 int(num**0.5)):
    if num % i == 0:
      break
  else:
    prime_sum  = num

print(prime_sum)

CodePudding user response:

You're not checking whether the inner loop found a factor or not before adding num to sum.

You can use the else: block of a loop to tell whether the loop finished or stopped due to break.

sum = 2

for num in range(3, 2000000, 2):
    for i in range(2, 1 int(num**0.5)):
        if num % i == 0:
            break
    else:
        sum  = num

print(sum)

CodePudding user response:

You're breaking out of the inner loop if the number is not prime, but then are still executing the line

sum  = num

There are multiple solutions to this.

  1. Moving the primality test to a function
def is_prime(x):
    for i in range(2, int(x ** 0.5)   1):
        if x % i == 0:
            return False
    return True
sum = 2
for num in range(3, 2000000, 2):
    if is_prime(num):
        sum  = num
print(sum)
  1. is_prime variable
sum = 2

for num in range(3, 2000000, 2):
  is_prime = True
  for i in range(2, 1 int(num**0.5)):
    if num % i == 0:
      is_prime = False
      break
  if is_prime:
    sum  = num

print(sum)
  1. all() and a list comprehension
sum = 2
for num in range(3, 2000000, 2):
    if all([num % i != 0 for i in range(int(x ** 0.5)   1)]):
        sum  = num
print(sum)
  • Related