I’m trying to make a show that gets an n number and returns all the cousins up to n, but I don’t know what’s going wrong

Asked

Viewed 48 times

0

numero = int(input('Digite um número: '))

lista_numeros = list(range(1, numero + 1))

primos = []

divisores = 0 

for n in lista_numeros: 
    for count in range (2, n): 
        if (numero % count == 0): 
            divisores =+ 1 

    if divisores == 0: 
        primos.append(n)


print(primos)

2 answers

0

Your code does not return the right answer. If you haven’t yet, I suggest you test this code:

def primo(numero):
    div = 0
    for n in range(1, numero+1):
        if numero % n == 0:
            div += 1 
    return div

numero = int(input('Digite um número: '))
lista = [x for x in range(1, numero)]
primos = []

for n in lista:
    div = primo(n)
    if div == 2:
        primos.append(n)

print(primos)

In function primo(numero) We received a number to verify if he is cousin or not. As we know, a prime number is one that is divisible only by 1 or by itself, that is, it only has 2 divisors. So in our function we start a splitter counter div 0 and we analyze how many divisors the number passed per parameter has, running from 1 to it. If it is divisible we increment our counter div.

We received a number in the variable numero and then create a list that goes from 1 to the number given. Here I used list comprehension to generate the list. In the variable primos create a list to store the primes and then just go through the list of numbers and call the function primo(). If the function result is 2 it means that the number only has 2 divisors, so it is prime and is added to the list of prime numbers.

0

Your code has some errors, for example: change this =+ for +=. I made the following changes:

numero = int(input('Digite um número: '))

lista_numeros = list(range(2, numero + 1))

primos = []

divisores = 0

for n in lista_numeros:
    for count in primos:
        if (n % count == 0):
            divisores += 1

    if divisores == 0:
        primos.append(n)

    divisores = 0

print(primos)
  • Gosh, thank you so much! I’m right at the beginning yet, I took only a few lessons. Thank you very much!

  • You are welcome. And it is not necessary to check if it is divisible by all numbers greater than 1, only check with prime numbers.

Browser other questions tagged

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