Fix infinite loop

Asked

Viewed 66 times

-2

Hello,

I made a code for a function that loops infinity every time I call but I can’t figure out why. Follows the code:

def geraprimos(qtd, inicio, fim):
    lista = []
    while len(lista) < qtd:
        numero = random.randint(inicio, fim)
        metade = numero//2       
        for i in range(2, metade):
            if numero%i == 0:
                next
            elif i == metade:
                lista.append(numero)
    return lista
  • 1

    Should be range range(2, metade + 1), for the function range does not include the final delimiter in the iterator, so that if you use range(2, metade), i will never be equal to metade.

  • 2

    Generating a list of prime numbers by randomly drawing them is not a good idea. I recommend reading about more optimized algorithms for this, such as Sieve of Eratosthenes.

1 answer

0

Its function is in the infinite loop pq there is no change in its Loop condition, so it always stays the same.

In case the error is in range of your for. The function range takes the range of numbers counting with the first number. Example:

  • for x in range(3) = for x in range (0,3) -> x = [0,1,2] (result)

In your case (for i in range(2, metade):) the i will be 2 <= x < metade, so it will never be equal to variable metade and will never enter the condition elif i == metade: which also will not add to the list (lista.append(numero)) that will not alter the stopping condition of your while (while len(lista) < qtd), because your list will always be empty..

To fix this eh very simple, can be in the condition of for or of elif:

Method 01: sum +1 in the fr

def geraprimos(qtd, inicio, fim):
    lista = []
    while len(lista) < qtd:
        numero = random.randint(inicio, fim)
        metade = numero//2       
        for i in range(2, metade + 1):          # Alteração
            if numero%i == 0:
                next
            elif i == metade:
                lista.append(numero)
    return lista

Method 02: sum +1 in the elif

def geraprimos(qtd, inicio, fim):
    lista = []
    while len(lista) < qtd:
        numero = random.randint(inicio, fim)
        metade = numero//2       
        for i in range(2, metade):
            if numero%i == 0:
                next
            elif i == metade +1:                # Alteração
                lista.append(numero)
    return lista
  • 1

    Keep in mind the next used in this code...

  • Yes, eh vdd. I forgot to put this pq when I tested I took it out pq eh an unnecessary condition

Browser other questions tagged

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