Skip to content

math/greatest_common_divisor: add support for negative numbers #2628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 29, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add correction to gcd of negative numbers
  • Loading branch information
pikulet committed Oct 2, 2020
commit de154b2faed4b056396683dd2203b3018a3d2937
31 changes: 21 additions & 10 deletions maths/greatest_common_divisor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Greatest Common Divisor.

Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor

gcd(a, b) = gcd(a, -b) = gcd(-a, b) = gcd(-a, -b) by definition of divisibility
"""


Expand All @@ -20,31 +22,40 @@ def greatest_common_divisor(a: int, b: int) -> int:
1
>>> greatest_common_divisor(16, 4)
4
>>> greatest_common_divisor(-3, 9)
3
>>> greatest_common_divisor(9, -3)
3
>>> greatest_common_divisor(3, -9)
3
>>> greatest_common_divisor(-3, -9)
3
"""
return b if a == 0 else greatest_common_divisor(b % a, a)


"""
Below method is more memory efficient because it does not use the stack (chunk of
memory). While above method is good, uses more memory for huge numbers because of the
recursive calls required to calculate the greatest common divisor.
"""
return abs(b) if a == 0 else greatest_common_divisor(b % a, a)


def gcd_by_iterative(x: int, y: int) -> int:
"""
Below method is more memory efficient because it does not create additional
stack frames for recursive functions calls (as done in the above method).
>>> gcd_by_iterative(24, 40)
8
>>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40)
True
>>> gcd_by_iterative(-3, -9)
3
>>> gcd_by_iterative(3, -9)
3
"""
while y: # --> when y=0 then loop will terminate and return x as final GCD.
x, y = y, x % y
return x
return abs(x)


def main():
"""Call Greatest Common Divisor function."""
"""
Call Greatest Common Divisor function.
"""
try:
nums = input("Enter two integers separated by comma (,): ").split(",")
num_1 = int(nums[0])
Expand Down