Generate a list of prime numbers up to 1000. These numbers should form a list, Lprimos. then check in Lprimos whether it is prime or not

Asked

Viewed 213 times

-3

I created an algorithm that prints the list, but I’m having difficulty doing the repetition that does the list search, I’m using if X in List, but I’m not getting it, someone could help me?

The repetition would be S/N, S to continue and N to stop

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 = 1000

li = 2
LPrimos = []
while li <= num:
    if primo(li):
        LPrimos.append(li)
    li += 1

print(LPrimos)

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')


  • 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.

  • 1

    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.

  • 1

    In fact, what would that be for with the variable mult? He has no purpose in his code. He forgot to delete it?

  • 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?

  • 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. Convert num for entire before searching.

  • Got it, thank you very much.

  • 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?

  • You do the reading once out of of the loop.

Show 3 more comments

2 answers

2

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).

0

Understanding "Generate a list of prime numbers up to 1000" as a list of all prime numbers under 1,000, try:

def ehprimo(num,primos):
    for divi in primos:
        if num%divi == 0:
            return False
    return True

num,cont,primos = 2,1,[]
while num <= 1000:
    if ehprimo(num,primos) == True:
        cont += 1
        print(num)
        primos.append(num)
    num += 1
print(primos)

Browser other questions tagged

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