Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have some problem with my homework. It's about stop the loops

I'm in the middle of my homework. And i can't find out how to do this solution.

I have tried to used the break under for-statement but nothing return. The problem 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 to do it

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 don't know that i should put break in which lines (or i don't have to used it?) or i should created a function that called a minimum number of the list?

I'm sorry about my language and how silly i am at my programming skill I would accept every comment. Thank you

like image 980
KillingSpree Avatar asked Sep 09 '19 18:09

KillingSpree


2 Answers

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
like image 51
MrGeek Avatar answered Oct 29 '22 06:10

MrGeek


Thanks for saying it's homework! Makes it better to explain things in more detail than just giving an answer.

There are few things to explain:

1) n%33 is the remainder of dividing n by 33. So 66%33 is 0 and 67%33 is 1.

2) For loops are generally when you need to loop over a defined range (not always, but usually). E.g. "add up the first 100 integers". A while loop makes more sense here. It will definitely terminate, because at some point you'll get to 33 * 237.

3) if i%33 == 0 and i%237 == 0: means we want to do something when the number can be divided evenly (no remainder) by both 37 and 237.

n=1001
while True:
    if n%33==0 and n%237==0:
        print(n)
        break
    n+=1
like image 44
Ian McGowan Avatar answered Oct 29 '22 07:10

Ian McGowan