Skip to content
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

math/extended_euclidean_algorithm cannot properly handle negative numbers #2630

Closed
pikulet opened this issue Oct 2, 2020 · 1 comment
Closed

Comments

@pikulet
Copy link
Contributor

@pikulet pikulet commented Oct 2, 2020

image

Think there is a mistake in the algorithm implemented.
By definition, gcd (a,b) = gcd (a,-b) = gcd (-a,b) = gcd (-a,-b)

So for a = 1, b = 4, the gcd is 1.

eqn1: 0(4) + 1(1) = 1 (correct)
eqn2: 0(4) + 1(-1) = -1 (sign incorrect)
eqn3: -1(1) + 1(-4) = -5 (sign and value incorrect)
eqn4: 1(-1) + 0(-4) = -1 (sign incorrect)

@pikulet pikulet changed the title math/extended_euclidean_algorithm math/extended_euclidean_algorithm cannot properly handle negative numbers Oct 2, 2020
@dhruvmanila

Loading…

Member

@dhruvmanila dhruvmanila commented Oct 2, 2020

Hey, thank you for pointing this out. It also seems that the Euclidean algorithm for GCD is not able to handle negative numbers as well:

$ python greatest_common_divisor.py
Enter two integers separated by comma (,): -3,9
greatest_common_divisor(-3, 9) = -3
By iterative gcd(-3, 9) = 3

$ python greatest_common_divisor.py
Enter two integers separated by comma (,): 3,-9
greatest_common_divisor(3, -9) = 3
By iterative gcd(3, -9) = -3

$ python greatest_common_divisor.py
Enter two integers separated by comma (,): -3,-9
greatest_common_divisor(-3, -9) = -3
By iterative gcd(-3, -9) = -3

$ python greatest_common_divisor.py
Enter two integers separated by comma (,): 3,9
greatest_common_divisor(3, 9) = 3
By iterative gcd(3, 9) = 3

Can you make two separate PRs to correct the algorithms?

@dhruvmanila dhruvmanila linked a pull request that will close this issue Oct 5, 2020
13 of 14 tasks complete
dhruvmanila added a commit that referenced this issue Oct 7, 2020
* add type hints to math/extended euclid

* math/extended euclid - add doctest

* math/extended euclid: remove manual doctest

* change algorithm for negative numbers

* improve naming of variables

* Update extended_euclidean_algorithm.py

Co-authored-by: Dhruv <dhruvmanila@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

2 participants
You can’t perform that action at this time.