To resolve this issue I implemented the following code:
# Este programa calcula a soma dos "n" primeiros números primos.
def soma_primos(n):
li = 2
primos = list()
while len(primos) < n:
if primo(li):
primos.append(li)
li += 1
return sum(primos)
def primo(m):
i = 1
cont = 0
while i <= m:
if m % i == 0:
cont += 1
i += 1
if cont != 2:
return False
else:
return True
num = int(input('Desejas calcular a soma de quantos primeiros números primos? '))
print(f'A soma do {num} primeiros números primos são:\n{soma_primos(num)}')
Note that when we execute the code we receive the following message: Desejas calcular a soma de quantos primeiros números primos?
. At this point we must enter the quantity of the first prime numbers. Afterwards the quantity is passed as parameter to the function soma_primos()
. Getting there, the block while
will execute multiple iterations until the size of primos
be the predecessor of n
. For each iteration execution the block if
check whether the value of li
is cousin. At this time the function will be asked primo()
if the value li
is cousin. If the function response primo()
be it True, the corresponding value is added to the list primos
. These verification operations are carried out until the list primos
is complete. After the list primos
is complete will be calculated the sum of its values and then displayed the result to the user.
Testing the code
Example 1
typing the value...
3
We will obtain as sum the result
10
...and indeed the sum of 3 first cousins is:
2 + 3 + 5 = 10
Example 2
If we type
100
We will get the value as a result:
24133
For the sum of 100 first prime numbers is 24133.
OBSERVING
This code is sufficient to calculate the summing up of any n first numbers cousins.
Can do the table test of your code and post together in the question?
– Woss