Project Euler Problem #5 - Smallest Multiple (in Python)

  1. # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
  2. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */

  3. # returns smallest multiple that is evenly divisible by all numbers from 1 - n
  4. # returns -1 if multiple does not exist
  5. def findSmallestMultiple(n):
  6.     for i in range(n, factorial(n) + 1, n):
  7.         if isMultiple(i, n):
  8.             return i
  9.     return -1

  10. # checks every number between 1 and n to see if x is a multiple of every number
  11. # returns True if x is found to be a multiple of every number, and False if x is
  12. # found to not be a multiple of any number
  13. def isMultiple(x, n):
  14.     for i in range(1, n):
  15.         if x % i != 0:
  16.             return False
  17.     return True

  18. # returns the n factorial, or -1 if it does not exist
  19. def factorial(n):
  20.     if n > 1: return n * factorial(n - 1)
  21.     elif n >= 0: return 1
  22.     else: return -1

  23. print (findSmallestMultiple(10)) # 2520
  24. print (findSmallestMultiple(20))
DOWNLOAD

If you're running Python 2.x, the code above will fail for the second call of the function because the for-loop range will "contain too many items".
In that case, use the code below (while-loop instead of for-loop). If you're running Python 3.x, the code above will work just fine.

  1. # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
  2. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */

  3. # returns smallest multiple that is evenly divisible by all numbers from 1 - n
  4. # returns -1 if multiple does not exist
  5. # works up to n = 20 (long reaches maximum value for values > 20) */
  6. def findSmallestMultiple(n):
  7.     i = n
  8.     while i < factorial(n):
  9.         if isMultiple(i, n):
  10.             return i
  11.         i += n
  12.     return -1

  13. # checks every number between 1 and n to see if x is a multiple of every number
  14. # returns True if x is found to be a multiple of every number, and False if x is
  15. # found to not be a multiple of any number */
  16. def isMultiple(x, n):
  17.     for i in range(1, n):
  18.         if x % i != 0:
  19.             return False
  20.     return True

  21. # returns the n factorial, or -1 if it does not exist
  22. def factorial(n):
  23.     if n > 1: return n * factorial(n - 1)
  24.     elif n >= 0: return 1
  25.     else: return -1

  26. print (findSmallestMultiple(10)) # 2520
  27. print (findSmallestMultiple(20))
DOWNLOAD

              Created: February 16, 2014
Completed in full by: Michael Yaworski