mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Feature/update least common multiple (#1352)
* renamed module to extend the acronym * add type hints (will not work with Python less than 3.4) * update docstring * refactor the function * add unittests for the least common squares multiple
This commit is contained in:
parent
870eebf349
commit
3cc3531076
@ -1,34 +0,0 @@
|
||||
"""Find Least Common Multiple."""
|
||||
|
||||
# https://en.wikipedia.org/wiki/Least_common_multiple
|
||||
|
||||
|
||||
def find_lcm(num_1, num_2):
|
||||
"""Find the least common multiple of two numbers.
|
||||
>>> find_lcm(5,2)
|
||||
10
|
||||
>>> find_lcm(12,76)
|
||||
228
|
||||
"""
|
||||
if num_1 >= num_2:
|
||||
max_num = num_1
|
||||
else:
|
||||
max_num = num_2
|
||||
|
||||
lcm = max_num
|
||||
while True:
|
||||
if (lcm % num_1 == 0) and (lcm % num_2 == 0):
|
||||
break
|
||||
lcm += max_num
|
||||
return lcm
|
||||
|
||||
|
||||
def main():
|
||||
"""Use test numbers to run the find_lcm algorithm."""
|
||||
num_1 = int(input().strip())
|
||||
num_2 = int(input().strip())
|
||||
print(find_lcm(num_1, num_2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
44
maths/least_common_multiple.py
Normal file
44
maths/least_common_multiple.py
Normal file
@ -0,0 +1,44 @@
|
||||
import unittest
|
||||
|
||||
|
||||
def find_lcm(first_num: int, second_num: int) -> int:
|
||||
"""Find the least common multiple of two numbers.
|
||||
|
||||
Learn more: https://en.wikipedia.org/wiki/Least_common_multiple
|
||||
|
||||
>>> find_lcm(5,2)
|
||||
10
|
||||
>>> find_lcm(12,76)
|
||||
228
|
||||
"""
|
||||
max_num = first_num if first_num >= second_num else second_num
|
||||
common_mult = max_num
|
||||
while (common_mult % first_num > 0) or (common_mult % second_num > 0):
|
||||
common_mult += max_num
|
||||
return common_mult
|
||||
|
||||
|
||||
class TestLeastCommonMultiple(unittest.TestCase):
|
||||
|
||||
test_inputs = [
|
||||
(10, 20),
|
||||
(13, 15),
|
||||
(4, 31),
|
||||
(10, 42),
|
||||
(43, 34),
|
||||
(5, 12),
|
||||
(12, 25),
|
||||
(10, 25),
|
||||
(6, 9),
|
||||
]
|
||||
expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18]
|
||||
|
||||
def test_lcm_function(self):
|
||||
for i, (first_num, second_num) in enumerate(self.test_inputs):
|
||||
actual_result = find_lcm(first_num, second_num)
|
||||
with self.subTest(i=i):
|
||||
self.assertEqual(actual_result, self.expected_results[i])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
Loading…
Reference in New Issue
Block a user