The second for loop in this code counts only up to the value of x
because it will never need to go any further. Whenever finding prime numbers, you can use modulo (%
) because if x % n
never becomes 0 (other than when n = x), it's prime, which is shown in the else :
statement.
You will always get a remainder if n
> x
for x in range(2,10):
for n in range(2,x): # Only needs to mod up to the current number
if x % n == 0: # If it is possible to mod the number and not get a decimal
print(f"{x} = {n} * {x//n}")
break # stop running because this number isn't prime
else:
print(f"{x} is a prime number.")
Example of logic :
3 % 2 = 1 : 3 is prime
4 % 2 = 0 : 4 isn't prime
5 % 2 = 1, 5 % 3 = 2, 5 % 4 = 1 : 5 is prime
6 % 2 = 0 : 6 isn't prime
and so on.
Because of the way that the code is written, It doesn't need to go any further then the first sign of it not being prime.