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.
Gosh, thank you so much! I’m right at the beginning yet, I took only a few lessons. Thank you very much!
– jcmricci
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.
– Arthur Bacci