sbhayana26
sbhayana26

Reputation: 61

Finding the sum of primes below 10

>>> k=1
>>> sum=0
>>> for i in range (2,10):
        for j in range (2,i):
            if ((i%j)==0):
                k=0
    if (k==1):
        sum+=i


>>> print(sum)
    5

I don't know why, but this code, instead of giving 17 as an output, always gives 5.

Upvotes: 2

Views: 70

Answers (3)

Kasravnd
Kasravnd

Reputation: 107337

Along side the @Martijn Pieters answer that note the problem you can use a generator expression within sum :

>>> sum(i for i in range(2,10) if all(i%j!=0 for j in range(2,i)))
17

Upvotes: 0

Kurenai Kunai
Kurenai Kunai

Reputation: 1902

sum=0
limit=10
for n in range(2,limit+1):
  if all(n % i for i in range(2, n)):
    sum += n
print sum

Output: 17

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123420

You need to set your k flag back to 1 each time the for i loop moves to the next number:

for i in range (2,10):
    k = 1
    for j in range (2,i):
        if ((i%j)==0):
            k=0
    if (k==1):
        sum+=i

Without doing that your code only ever finds 5 to be a prime number, and ignores anything after that.

Note that in Python, 0 is considered false when used in a boolean context (such as an if statement), 1 is true, so you can just use if k:. Better still, use True and False and better variable names, such as is_prime rather than k. You can drop a lot of those parentheses:

sum = 0
for num in range (2, 10):
    is_prime = True
    for i in range (2, int(num ** 0.5) + 1):
        if not num % i:
            is_prime = False
    if is_prime:
        sum += num

I also made use of the fact that you only need to check up to the square root of a number to see if there are divisors, cutting your loops down significantly.

Last but not least, you can make use of the for ... else construct; if you use break in a for loop, the else branch never gets executed, but if the for loop completes to the end without breaking out, it is; this removes the need for a boolean flag:

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

Upvotes: 4

Related Questions