What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?
number = 0 found = False #starting value of 20 x 19 # because we need a number which # is both a multiple of 19 and 20 # and only numbers that are # multiples of 20 x 19 # fullfill this requirement curNum = 20 * 19 foundCur = False #only need to check 20-11, because all #numbers 10-1 equally divide the numbers #already in the list. checknumbers = [20,19,18,17,16,15,14,13,12,11] while not found: foundCur = True for i in checknumbers: if curNum % i > 0: foundCur = False break if foundCur: number = curNum found = True #only check multiples of 20 x 19 # because no other numbers will # be multiples of both 20 and 19 curNum += 20 * 19 print "The smallest number that can be evenly divided by the numbers 1-20 is %d " % (number,)
Pretty straight forward here. Although I had to do a couple optimizations to get it to run at a reasonable speed. The first optimization was to make it check in reverse order, if the number is divisible from the numbers 20 to 1, because less numbers will be divisible by the higher numbers, you end up doing less checks. The other optimization I did was to only check numbers that are multiples of 20, by starting at 20, and adding 20 each time. This way you don't check any numbers that can't possibly be divisible by at least 20. Then to make it even faster, I realized that you only have to check numbers that are multiples of 20 * 19, because no other numbers will be divisible by both 20 and 19. This cut down the processing time considerably. There's probably some tricky math you can do here to find the answer without any kind of brute force whatsoever, but I'm not really that fluent in my math to go about figuring it out right now. The last change I did was to only check the numbers from 20-11, since the numbers 10-1 are already covered by the other set. This doesn't speed things up much, and only makes a difference once you have actually gotten to the number you are looking for.