I came through a problem in programming which needs Extended Euclidean Algorithm, with a∗s+b∗t=gcd(|a|,|b|) for b≤0 and a≥0
With the help of this post: extended-euclidean-algorithm-with-negative-numbers
I know we can just move the sign towards t and just use normal Extended Euclidean Algorithm and use (s,−t) as solution
However in my scenario, there is one more condition: I would like to find the minimum non-negative solution, i.e. (s,t) for s,t≥0
And my question is how to find such minimum (s,t)?
Sorry if it sounds too obvious as I am dumb :(
Thanks!
Answer
Fact 1: One nice property of the Extended Euclidean Algorithm is that it already gives minimal solution pairs, that is, if a,b≥0, |s|<bgcd(a,b) and |t|<agcd(a,b)
Fact 2: If (s,t) is a solution then (s+k∗bgcd(a,b),t−k∗agcd(a,b)),k∈Z is also a solution.
Combining the two facts above, for your case in which a≥0 and b≤0, compute the pair (s,t) using the extended algorithm on (|a|,|b|), then either:
- s≥0,t≤0, in this case (s,−t) is the solution you want.
- s≤0,t≥0, in this case (s+|b|gcd(|a|,|b|),−t+|a|gcd(|a|,|b|)) is your desired solution.
No comments:
Post a Comment