Ask your own question, for FREE!
Computer Science 17 Online
OpenStudy (anonymous):

Hello, Ive been trying to find the smallest number that is evenly divisible by numbers 1-20 with python. Reply if you have some knowledge on problems like this. My attempt: x=2520 >>> y=1 >>> while y<20: y+=1 x+=1 if x>2520 and x%y is 0: print str(x)+ "is evenly divisible with"+str(y) else: print "This code was uneffective"

OpenStudy (anonymous):

Here is the first somewhat naive option, which gets to 18 fairly quickly but takes a long time to get to 20. I suggest running it and looking at the output. div_min = 0 num = 1 while True: divisable = True i = 1 while i < 21 and divisable: if num % i != 0: divisable = False elif i > div_min: div_min = i print("First num divisable by 1 to", i, "is", num) i += 1 if i == 21: print("Divisable by 1 to 20:", num) break num += 1 After looking at the output you realize that each new divisable is a multiple of the previous one so instead of incrementing by 1 each time on last line, increment by previous divisable. Also, no sense checking all previous divisors so i = 1 becomes i = div_min +1. And since we can do much higher numbers now, let's implement max div so we can do more than just 1..20. Code below does 1..1000. Also comment out first print as we probably don't want to see all 1000. div_min = 0 div_num = 1 #previous divisable num = 1 max_div = 1000 #max divisible while True: divisable = True i = div_min + 1 #only check divisors not previously checked while i < max_div + 1 and divisable: #use max_div now if num % i != 0: divisable = False elif i > div_min: div_min = i div_num = num #save previous divisable #print("First num divisable by 1 to", i, "is", num) i += 1 if i == max_div + 1: #use max_duv now print("Divisable by 1 to", max_div, ":", num) #use max_div now break num += div_num #increment by previous divisable

OpenStudy (anonymous):

Is it supposed to say "('Divisable by 1 to 20:', 1)" as an output?

OpenStudy (anonymous):

The second one, if you have max_div = 20 will output "Divisable by 1 to 20 : 232792560"

OpenStudy (anonymous):

Ok

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!