I can’t make the sum of the first 100 prime numbers, where am I wrong?

Asked

Viewed 693 times

0

#python3.7

cont = 0
cont_100 = 0
primos = 0
num = 1
soma = 0
while True:
    primos += 1

    while primos != num:
        if primos % num == 0:
            num += 1
            cont += 1
    if cont == 2:
        soma += primos
    num = 1

    cont_100 += 1
    if cont_100 == 100:
        break
print(soma)
  • Can do the table test of your code and post together in the question?

3 answers

3

There are some errors in your code:

  • The cont has to be reset with each iteration;
  • The condition of the second while should be primos >= num;
  • The variable num should be incremented at each iteration of the internal loop, not only when primos % num == 0;
  • And you can only increase cont_100 when the number is prime, i.e., in the if cont == 2.

Follow the version of your corrected code:

#python3.7

cont_100 = 0
primos = 0
num = 1
soma = 0
while True:
    primos += 1
    cont = 0

    while primos >= num:
        if primos % num == 0:
            cont += 1
        num += 1

    if cont == 2:
        soma += primos
        cont_100 += 1
    num = 1

    if cont_100 == 100:
        break
print(soma)

And a version with some changes I made:

#python3.7

cont_100 = 0
primos = 0
soma = 0

while cont_100 < 100:
    primos += 1
    num = 1
    cont = 0

    while primos >= num/2:
        if primos % num == 0:
            cont += 1
        num += 1

    if cont == 2:
        soma += primos
        cont_100 += 1

print(soma)
  • Perfect! I still managed to solve with while to repeat the 100x and a for in range to test if the number is prime. But that your way just with while got better. Thank you!!

0

Follow my solution, please test.

Basically I test if a number is prime and if it is added to the list primos.

When the list primos has 100 elements the loop ends and displays the sum of all elements in the list primos.

primos = []
numero = 0

while len(primos) != 100:        

    total = 0

    for n in range(1, numero + 1):        
        if numero % n == 0:
            total += 1        

    if total == 2:
        # É primo porque o resto da divisão foi igual a zero duas vezes
        # Em outras palavras, o número foi divisivel por 1 e por ele mesmo
        primos.append(numero)

    numero += 1

print(sum(primos))
  • 2

    You can make it faster by calculating up to number / 2. Because there is no way a number can be divisible by a number greater than its half.

  • Kevin, thanks for the contribution! How would you look? I couldn’t get here...

  • 3

    In fact you only need to go to the square root of the number, and skipping 2-in-2 (there is no reason to divide by even numbers, you can test if it is even before doing the for, thus already avoids the loop if the number is even - except if it is 2, which is the only prime that tb is even, and even makes up for making a if specific before the for). If you really want to use more efficient algorithms, there are several listed here

  • Got it, I’ll see the algorithms you suggested. Grateful hkotsubo!

  • Thank you very much! It was very similar to what I managed to solve. The difference is that I didn’t use (by not knowing) the list... Thank you so much for the help!

0

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.

Browser other questions tagged

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