"""
divisible_by_1_to_n.py
Ask for an integer n.
Then find and print the first integer divisible by 1 through n.
(The brute force method here is *not* an efficient way to solve this problem.)
programing class exercise, Jim Mahoney | Oct 3 2011 | GPL
"""
def x_is_divisible_by_y(x, y):
""" Return True if x is divisible by y.
>>> x_is_divisible_by_y(10, 3)
False
>>> x_is_divisible_by_y(10, 5)
True
"""
return x % y == 0
def x_is_divisible_by_1_to_n(x, n):
""" Return True if x is divisible by y.
>>> x_is_divisible_by_y(10, 3)
False
>>> x_is_divisible_by_y(10, 5)
True
"""
for i in range(1, n+1):
if not x_is_divisible_by_y(x, i):
return False
return True
def first_1_to_n_multiple(n):
""" Return first integer divisible by 1 through n
>>> first_1_to_n_multiple(3)
6
>>> first_1_to_n_multiple(10)
2520
"""
x = n
while True:
if x_is_divisible_by_1_to_n(x, n):
return x
x = x + 1
def main():
n = input("What is n? (10) ")
answer = first_1_to_n_multiple(n)
print "%i is divisible by all the integers up to %i" % (answer, n)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
syntax highlighted by Code2HTML, v. 0.93pm6