fork download
  1. #!/usr/bin/env python
  2. import timeit
  3. from functools import partial, reduce
  4.  
  5. def gcd(a, b):
  6. """Greatest common divisor (factor)."""
  7. while b: # Euclid's algorithm
  8. a, b = b, a % b
  9. return a
  10.  
  11. def lcm(*args):
  12. """Least common multiple."""
  13. # lcm(a, b, c) == lcm(lcm(a, b), c)
  14. return reduce(lambda a, b: a * b // gcd(a, b), args)
  15.  
  16. def f(n):
  17. """Smallest positive number evenly divisible by all numbers from 1
  18. to n including.
  19. """
  20. return lcm(*range(1, n + 1))
  21.  
  22. print(f(10)) # -> 2520
  23. print(f(50)) # -> 3099044504245996706400
  24.  
  25. def measure():
  26. for n in [10, 50, 100]:
  27. print("%3d: %5.2f microseconds" % (n, 100*timeit.timeit(partial(f, n),
  28. number=1000*10)))
  29. measure()
  30.  
Success #stdin #stdout 1.87s 9888KB
stdin
Standard input is empty
stdout
2520
3099044504245996706400
 10: 10.41 microseconds
 50: 53.56 microseconds
100: 117.02 microseconds