python 3.x - Finding the sum of primes below 10 -
>>> k=1 >>> sum=0 >>> in range (2,10): j in range (2,i): if ((i%j)==0): k=0 if (k==1): sum+=i >>> print(sum) 5
i don't know why, code, instead of giving 17 output, gives 5.
you need set k
flag 1
each time for i
loop moves next number:
for in range (2,10): k = 1 j in range (2,i): if ((i%j)==0): k=0 if (k==1): sum+=i
without doing code ever finds 5
prime number, , ignores after that.
note in python, 0 considered false when used in boolean context (such if
statement), 1 true, can use if k:
. better still, use true
, false
, better variable names, such is_prime
rather k
. can drop lot of parentheses:
sum = 0 num in range (2, 10): is_prime = true in range (2, int(num ** 0.5) + 1): if not num % i: is_prime = false if is_prime: sum += num
i made use of fact need check square root of number see if there divisors, cutting loops down significantly.
last not least, can make use of for ... else
construct; if use break
in for
loop, else
branch never gets executed, if for
loop completes end without breaking out, is; removes need boolean flag:
sum = 0 num in range (2, 10): in range (2, int(num ** 0.5) + 1): if not num % i: break else: sum += num
Comments
Post a Comment