2
>>> 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.

sbhayana26
  • 61
  • 1
  • 7

3 Answers3

4

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
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
  • Great answer Mr. new moderator – Stasel Apr 29 '15 at 07:39
  • Thank you! Your answer helped. – sbhayana26 Apr 29 '15 at 07:42
  • And what do i do if i need to find the summation of primes below a very big number, for instance, one million? My code, after making the changes regarding the 'k' variable, isn't working in this case. – sbhayana26 Apr 29 '15 at 07:47
  • @sbhayana26: finding all primes up to 1 million takes a little while with this method. If you used my method (only test up to the square root) it'll be a little faster. The sum is 37550402023, it works just fine. There are [faster ways still](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n) using sieves. – Martijn Pieters Apr 29 '15 at 07:50
0

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
kasravnd
  • 94,640
  • 16
  • 137
  • 166
0
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
Kurenai Kunai
  • 1,786
  • 2
  • 10
  • 22