To generate the list with all primes up to a certain number, you can use better algorithms, such as the Eratosthene Sieve (it even has a complete implementation in this answer - but how looks like be an exercise, maybe you can’t use it). But just to give another alternative better than your code, just consider that:
- With the exception of 2, all other even numbers are not primes. That is, from 3, I just need to test the odd numbers.
- I do not need to test whether the number is divisible by even numbers (for in this case it would be divisible by 2, and therefore even, and therefore not prime). In fact, I just need to test if it is divisible by some prime number. Any other test is redundant.
And since you are already building a list of all prime numbers, just use it in the check itself:
# adicionar n na lista de primos, caso seja
def adiciona_se_primo(n, primos):
limite = n // 2
# verifica se n é divisível por algum dos números primos já encontrados
for p in primos:
# se já passou da metade de n, não terá mais nenhum divisor e posso parar o for
if p > limite:
break # sai do loop, já sei que é primo
if n % p == 0:
return # retorna (não é primo)
primos.append(n)
LPrimos = [2] # já posso começar com o 2 (o único número par que é primo)
# constrói a lista com todos os primos até 1000
for n in range(3, 1000, 2): # range de 2 em 2 para só pegar os ímpares
adiciona_se_primo(n, LPrimos)
First I start the list of cousins with the 2. Then I make one loop with odd numbers up to 1000 (starting from 3), and I add the primes found in LPrimos
. The interesting thing is that I use the list of cousins myself to check whether n
is cousin, and update this list if.
See that in function adiciona_se_primo
I just check if n
is divisible by some prime number, as I do not need to test whether it is divisible by all numbers, is redundant. And I don’t have to go all the way if I’m past the half of n
, from then on there will be no divisor of n
and so I already know he’s cousin and I can interrupt the loop.
At the end, we’ll have the list of all cousins under 1000.
Now the second part. See your loop:
num = int(input('digite o número, digite "0" para parar o programa'))
while num != 0:
if num in LPrimos:
print('É primo')
else:
print('Não é primo')
While num
is different from zero, the while
continues to rotate. But inside the loop you never change the value of num
. That is, if he is not zero, he enters the while
and never comes out again. Probably what you want is something like this:
# agora que já tenho a lista de números primos, basta fazer o *loop*
while True:
num = int(input('digite o número, digite "0" para parar o programa'))
if num == 0:
break
if num in LPrimos:
print(f'{num} é primo')
else:
print(f'{num} não é primo')
I mean, I read the value within of while
, and if it’s zero, I use break
to get out of loop.
Some people "don’t like" you break
and prefer to do something like this:
num = 1
while num != 0:
num = int(input('digite o número, digite "0" para parar o programa'))
if num != 0:
if num in LPrimos:
print(f'{num} é primo')
else:
print(f'{num} não é primo')
But I think worse. First because you have to initialize the variable with some artificial value just to enter the loop, and then you have to put a if
the more not to consider zero (otherwise he would print that zero is not prime, but I understand that zero only serves to terminate and therefore should not be tested).
I understood, but I must then create an input, for example 875, and have the algorithm look in this list of prime numbers if the number 875 is inside it. And if you are, print that you’re cousin, if not print that you’re not.
– Luiz Henrique
if X in Lista
It should work, considering that "list" is actually "lprimos". If it is not working, please update the question with this code snippet as well.– Woss
In fact, what would that be
for
with the variablemult
? He has no purpose in his code. He forgot to delete it?– Woss
Yes, I updated the question, when I give a run, and I test, even putting a number that is inside the list, it marks as if it is not prime. And how could I also do a repeat for s/n?
– Luiz Henrique
Then, the return of the function
input
is always a string. If you type 37,num
will be"37"
. Because your list is made up of integers and you are searching for a string you will never find. Convertnum
for entire before searching.– Woss
Got it, thank you very much.
– Luiz Henrique
I put it to stop when 0, but the program generates a loop and does not stop, it keeps printing the answer endlessly, what is the reason for it?
– Luiz Henrique
You do the reading once out of of the loop.
– anonimo