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
Should be range
range(2, metade + 1)
, for the functionrange
does not include the final delimiter in the iterator, so that if you userange(2, metade)
,i
will never be equal tometade
.– Andre
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.
– Woss