-2

Could anybody explain this to me? I'm not sure what the second for loop does.

for x in range(2,10):
    for n in range(2,x):
        if x % n == 0:
            print(f"{x} = {n} * {x//n}")
            break
    else:
        print(f"{x} is a prime number.") 
Nathan
  • 3,558
  • 1
  • 18
  • 38

3 Answers3

0

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.

Community
  • 1
  • 1
CanadianCaleb
  • 136
  • 10
0

The first for loop lists what numbers are checked. So you check if 2, 3, 4, 5, 6, 7, 8 and 9 are prime.

The second for loop is used to establish if the number is prime. It does this by checking if it can be divided by any number smaller than itself and larger than 1. Fore example:

We want to check if 9 is prime. So we check 2, 3, 4, 5, 6, 7 and 8. We find that 9%3==0, so we know 9 is not prime.

Nathan
  • 3,558
  • 1
  • 18
  • 38
0

The first loop dictates the numerator of your fraction, the second loop runs through the possible denominators of the fraction. If the division cannot be done without a remainder for all possible denominators then it'll print the formula and break the loop.

Jkind9
  • 742
  • 7
  • 24