0
sum_ans=17
for i in range(11,2000000):
    for j in range(2,int(i**0.5)):
        if i%j==0:
            break
    else:
        sum_ans+=i
print(sum_ans)

The code i have return gives answer 143064094781 and the correct answer is 142913828922 but i can not figure out where i have gone wrong. So can any one help me.

Kishan
  • 1
  • 1
  • 3
    I think i**0.5 + 1 should do the job, because the second argument of range() is exclusive. – Creepsy Aug 02 '20 at 12:18
  • Your `17` includes 2, which is the only even prime. That means you only need to try `i` odd: 11, 13, 15, ... because all the even numbers > 11 are composite. Given that `i` is odd, there is no need to test `j` == 2; start at 3 and again only work with odd values: 3, 5, 7, 9, ... – rossum Aug 02 '20 at 16:48

2 Answers2

0

Range's stop parameter is exclusive. This means that your code is only calculating j from 2 to 1 less than i**0.5. To fix this you can add 1, meaning that your end code will look a little like this, providing the correct output of 142913828922:

sum_ans=17
for i in range(11,2000000):
    for j in range(2,int(i**0.5+1)):
        if i%j==0:
            break
    else:
        sum_ans+=i
print(sum_ans)
Minion3665
  • 727
  • 8
  • 23
  • Why raise i to the .5? What is i**0.5? – BrianBeing Feb 05 '22 at 19:14
  • @BrianBeing a number to the power of 0.5 is the same as saying the square root of that number; when looking at primes [you only need to check up to the square root of the number](https://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr) to see if it's prime – Minion3665 Feb 06 '22 at 00:28
0

What about about this:

def isPrime(x):
    prime = True
    for i in range(2, x):
        if x % i == 0:
            prime = False
            break
        else:
            continue
    return prime

primes = (a for a in range(2, 2000000) if isPrime(a))
print(sum(primes))
# output
142913828922

This code will take a few minutes to execute. Buckle up!!