0
I decided to create a script to detect prime numbers, but in order to really understand what I’m doing I created something from scratch, something I thought.
At first my program worked, but I noticed that it "hangs" in large numbers, above 5 digits, as if it were consuming all the memory of the PC, after a while it unlocks and finally shows the result, I don’t know if this is normal. Finally, I would like to improve this code, in order to understand in a very didactic way what I am doing, if possible, someone who can help me visualize the reason for the "lock", and its correction. Follows:
numero = int(input('Digite um numero:'))
div = 0
cont = numero
while cont >= 1:
if numero % cont == 0:
div += 1
cont += -1
if div < 2 or div > 2:
print('Não é primo!')
elif div == 2:
print('É primo')
Another solution I thought was this, but it hangs the same way:
numero = int(input('Digite um numero:'))
div = 0
cont = numero
while div < 2:
if numero % cont == 0:
div += 1
cont += -1
if div < 2 or div > 2:
print('Não é primo!')
elif div == 2:
print('É primo')
I’m sorry, I still can’t post codes correctly on this site, I hope you can see the identations...
The suggestion "you could improve performance by dividing this number only by the numbers that go up to half of it" is very good. If instead of half it is only to the square root, the code will be even more optimized.
– Marcus Nunes
True, it would be much more optimized, I don’t know this property of square roots, you have link some content that talks about it?
– Emanoel Vieira