Luke_V
Luke_V

Reputation: 79

Why are these two codes different?

Probably a simple question, but I thought I was doing the same thing while instead i get two different answers, I am trying to calculate the sum of all the prime numbers below 2 million.

## THIS WORKS ##
import sympy
ans = 0
for n in range(0, 2000000):
    if sympy.isprime(n):
        ans += n
print(ans)

## THIS ONE DOESNT< BUT IT LOOKS THE SAME TO ME ##
ans = sum(sympy.isprime(num) for num in (range(0, 20000000)))
ans

Upvotes: 0

Views: 92

Answers (4)

Talha A.
Talha A.

Reputation: 115

In the first instance you're summing over the value, and the second instance you sum over an integer cast of a boolean.

The following code should do what you expect:

ans = sum(n for n in range(0, 2000000) if sympy.isprime(n))

Upvotes: 3

John Szakmeister
John Szakmeister

Reputation: 47102

In the second version, you're summing up whether it's prime or not (counting the number of primes), not the value of the primes. To do that, use this:

ans = sum(num for num in (range(0, 20000000) if sympy.isprime(num)))

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81674

The first example sums the prime numbers.

The second example counts them. sympy.isprime(num) returns either True or False (1 or 0) and sum sums these ones and zeros, effectively counting the prime numbers in that range.

A one liner equivalent for the first example would be

sum(num for num in range(0, 20000000) if sympy.isprime(num))

Upvotes: 0

WojciechR
WojciechR

Reputation: 333

In the first code, you sum the primes up to 2000000. In the second, you sum booleans saying whether a number is prime. In other words, first code gives a sum of primes, the second gives their number.

Upvotes: 0

Related Questions