Skip to content

Instantly share code, notes, and snippets.

@lifeofchrome
Created July 21, 2017 18:52
Show Gist options
  • Save lifeofchrome/4880e6054ebdebfa807f322a76088fb9 to your computer and use it in GitHub Desktop.
Save lifeofchrome/4880e6054ebdebfa807f322a76088fb9 to your computer and use it in GitHub Desktop.
LCM and GCF tools for lists of integers
"""LCM and GCF tools for lists
Made by lifeofchrome on July 21, 2017
"""
"""lcm(numbers) takes in a list of integers and returns their least common multiple
The function loops through the minimum possible LCM and increments by 1 until the first multiple is found
test is the current test value
correct is set to correct until there's a number that isn't a multiple
"""
def lcm(numbers):
test = max(numbers)
while True:
correct = True
for i in numbers:
if test % i != 0:
correct = False
if correct:
return test
test += 1
print(lcm([4, 9, 14]))
"""factors(number) returns a list of factors for an integer by looping through each integer less than number and
appending all factors to factors_list.
"""
def factors(number):
factors_list = []
for i in range(1, number + 1):
if number % i == 0:
factors_list.append(i)
return factors_list
"""gcf(numbers) takes in a list of numbers and returns their greatest common factor by calling factors() for each number
and adding common factors from the previous numbers to the set, and then returning the greatest value in the set.
"""
def gcf(numbers):
common_factors = set(factors(numbers[0]))
factors_set = set()
for number in numbers:
for factor in factors(number):
factors_set.add(factor)
common_factors = common_factors & factors_set
factors_set = set()
return max(common_factors)
print(gcf([24, 1024, 96]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment