pythonfor-loopmathwhile-loopbreak

How to find the lowest number that is divisible by two other numbers?


The requirement for my program is:

Complete the following program so that the loop stops when it has found the smallest positive integer greater than 1000 that is divisible by both 33 and 273.

This is my code that I have tried so far:

n = 1001 #This one is required

while True: #This one too
    for i in range(n,___): # I don't know what should i put in the blank
          if i%33 == 0 and i%273 == 0: # I really confused about this line
              break # Should i break it now?, or in the other lines?
print(f"The value of n is {n}") #This one is also required

I have tried to use the break under for-statement but nothing returns. I don't know where I should put a break, in which lines or if I even need it at all.

How should I write the loops to get the correct result?


Solution

  • You already have a while True: loop, you don't need the inner for loop to search for your number, just keep incrementing n in the while loop instead of adding a new counter, when the number you're looking for is found, the infinite while True: loop will stop (using break), and so your print statement will be executed:

    n = 1001  #  start at 1001
    
    while True:  #  start infinite loop
        if n % 33 == 0 and n % 273 == 0:  #  if `n` found
            break  #  exit the loop
        n += 1  #  else, increment `n` and repeat
    
    print(f"The value of n is {n}")  #  done, print the result
    

    Output:

    The value of n is 3003