The sum of the N first prime numbers

Asked

Viewed 888 times

2

Write a program that reads a non-negative integer and print the sum of the N first prime numbers.

I am not able to add the N first prime numbers but add up to the prime number typed.

If I type 5 for example appears 2 3 5 and the sum that is 10. But in the case would have to appear 2 3 5 7 11 and the sum that would 28.

My code:

n = int(input('Digite um número inteiro positico: '))
soma = 0
for num in range(2, n + 1):
    primo = True
    for i in range(2, num):
        if num % i == 0:
           primo = False
    if primo:
        print(num)
        soma += num
print(soma)

1 answer

3


I would do so:

n = int(input('Digite um número inteiro positivo: '))
soma = 0
conta = 0
num = 2
while conta < n:
    primo = True
    for i in range(2, num):
        if num % i == 0:
           primo = False
           break
    if primo:
        print(num)
        soma += num
        conta += 1
    num += 1
print(soma)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The counting of how many numbers are primes. and therefore summed. must be independent of the evolution of the numbers that are considered primes. The question code is stopping when the number that can be prime reaches the limit. So num will evolve at each step as the code is doing, but the count of how many is picking up is the condition for ending the repetitions.

You could use it alone for but would have to for a if, I saw no advantage.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.