Reputation: 729
Can anyone tell me why the print statement in reached for every iteration of the for loop, even though the conditions aren't met?
from math import *
def sumOfPrimes():
divisor = 2
for n in range(2, 100):
if n % divisor != 0 and n != divisor:
divisor += 1
if divisor == n:
print (n, divisor)
divisor = 2
else:
divisor = 2
Upvotes: 0
Views: 176
Reputation: 362
lets look at the number 3. the divisor is still 2.
(n % divisor != 0 and n != divisor) = (3 % 2 != 0 and 3 != 2) = True
divisor += 1 (divisor is now 3.)
(divisor == n) = (3 == 3) = true
print (n, divisor) = print(3,3)
now at number 4:
(n % divisor != 0 and n != divisor) = (4 % 3 != 0 and 4 != 3) = True
divisor += 1 (divisor is now 4.)
(divisor == n) = (4 == 4) = true
print (n, divisor) = print(4,4)
and so on. that's why the print statement is reached for every iteration of the for loop.
if you want to calculate the sum of the primes from 2 to 100 you can use another loop with another var, which run from 2 to sqrt(n) and checks if the number is dividable with any of them. that way you can determinate if the number is prime or not, and add only primes to the sum.
from math import *
def sumOfPrimes(Number):
Sum = 0
for n in range(2, Number+1): #range doesnt count the last number so I added 1 to Number.
if sqrt(n)<2: Sum += n;
else:
prime = True;
for i in range(2, int(sqrt(n))+1): #range takes only int, the +1 is like the previous one.
if n % i == 0:
prime = False; #the number is not prime.
if prime: Sum+=n; print n;
return Sum;
print sumOfPrimes(100);
Upvotes: 2
Reputation: 281476
if n % divisor != 0 and n != divisor:
n % divisor != 0
is true if divisor
isn't a divisor of n. For example, this will be true if divisor
is 2 and n
is 3. On every iteration of the loop after the first, this will trigger, because divisor
will be n-1
.
divisor += 1
On every iteration of the loop after the first, divisor
will be n-1
right before this line and n
right after. I don't know why you're doing this.
if divisor == n:
This will be true, so
print (n, divisor)
this will happen.
Upvotes: 2
Reputation: 500673
You are -- I would imagine unintentionally -- reusing the variable called n
for two different things. One is the argument to the function, and the other is the loop variable:
def sumOfPrimes(n):
...
for n in range(2, int(sqrt(n))):
...
You need to figure out which is which, and separate them by renaming one of them throughout the code.
Upvotes: 1