I need to count the prime numbers to a certain number n

Asked

Viewed 174 times

-1

Write the n_primes function that takes as argument an integer greater than or equal to 2 as parameter and returns the number of primes that exist between 2 and n (including 2 and, if applicable, n).

def n_primos(x):
começo = 1
divisivel = 0
naodiv = 0
while começo <= x: 
    fator = 2 
    if começo % fator == 0: 
        divisivel += 1  
    else:
        naodiv += 1  
    começo += 1
    fator += 1
return naodiv

What am I doing wrong? Someone please help me :(

  • The duplicate suggested above tells how to get the prime numbers, but it is not difficult to adapt the existing answers to compute the quantity as well, since the greatest difficulty seems to be the algorithm to determine whether the number is prime, and this is already covered by the answers

1 answer

-1

manow I did not understand its logic to count the prime numbers which are divisible numbers only by themselves and 1. But to help you, you are all the time assigning value to the "naodiv" every time the number is odd, since you the "factor" always goes is worth 2. The last line inside the 'while' (factor += 1) has no effect, since every time the loop happens the "factor" will receive the value 2. See if that helps you.

Browser other questions tagged

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