Trying to write a program that prints the smallest number divisable by all numbers from 1-20. Works for 1-10 but not for this. Why?

Hello,

I was trying to write a program in python to print the smallest number that is evenly divisable by all the numbers from 1-20. It is a project eluer question, no. 5.

Context: I can write the program to print the smallest number evenly divisable by all the numbers from 1-10. It even works for 1-15 and 1-16 (although latter takes a little time), but it doesn’t work for 1-20. Why?
I tried to writer the program but it doesn’t work. It doesn’t even show an error.

Code

Here is the code:

a = 1
b = 1

while (b<21):
    if (a%b==0):
        b = b+1
    else: 
        a = a+1
        b = 1
print ("The smallest number that is evenly divisable by all the numbers from 1 to 20 is: ", a)

Here is the output:

#Like it shows nothing. I am using python comment to explain that.  It just stays blank.

But if I use the same code to figure out the smallest number divisable by all numbers from 1-10 then it works:

a = 1
b = 1

while (b<11):
    if (a%b==0):
        b = b+1
    else: 
        a = a+1
        b = 1
print ("The smallest number that is evenly divisable by all the numbers from 1 to 20 is: ", a)

Output:

The smallest number that is evenly divisable by all the numbers from 1 to 20 is:  2520 #which is the correct answer. 

And If I do the same thing for 1-15 or 1-16 It works there too. But sometimes it can take some time.

Note: While I was typing this post I ran the 1-20 code again and it did show a result after quite some time (like at least 30 seconds to a minute) but I think the answer was wrong.

Why does this happen?: Now does this happen cause there is something wrong with my code (which should’ve been caught when I ran the other test codes) or it just takes time. Why does it happen?

Thank you
Joyeta

Hi. I think your code is working fine. That is because when you higher the number that is divisible, if you would wait a bit the results shown would be considerably higher then the previous result. This causes the code to run for much longer therefor it takes longer to produce the result. then again I may very possibly be wrong being as I am not very advanced in python and didn’t think through the mathematical logic of your program. It is very possible that there is a better way to do this. Here’s wishing you luck in solving this issue.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.