-2

Assume the availability of a function is_prime. Assume a variable n has been associated with positive integer. Write the statements needed to compute the sum of the first n prime numbers. The sum should be associated with the variable total.

Note: is_prime takes an integer as a parameter and returns True if and only if that integer is prime.

So far I have:

i=2
count=0
total=0
while (count<n):
    if(is_prime(i)):
        total+=1
        count+=1
    i+=1

Where am I missing the problem.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Randy
  • 5
  • 1
  • 5

1 Answers1

1

to fix your existing ... just add i to total

i=2
count=0
total=0
while (count<n):
    if(is_prime(i)):
        total+=i
        count+=1
    i+=1
print total

you could make it much better by making a generator to yield primes forever

def primes():
   for i in itertools.count(1):
       if is_prime(i):
          yield i

then you could make n_primes that yields the first n primes

def n_primes(n):
    return [prime for prime,_ in zip(primes(),range(n))]

then lastly you just sum it

print sum(n_primes(N))
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179