Last active
January 6, 2022 01:49
-
-
Save MikuroXina/f4205a25d8a0e6411a5fa0a8a46990f5 to your computer and use it in GitHub Desktop.
The implementation of Extended Euclidean algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use num::{Integer, One, Zero}; | |
| pub trait GcdNum: Copy + Integer + One + Zero + std::ops::SubAssign {} | |
| pub fn gcd_ext<T: GcdNum>( | |
| a: T, | |
| b: T, | |
| ) -> (T, T) { | |
| fn inner<T: GcdNum>( | |
| a: T, | |
| b: T, | |
| x: &mut T, | |
| y: &mut T, | |
| ) -> T { | |
| if b == T::zero() { | |
| *x = T::one(); | |
| *y = T::zero(); | |
| a | |
| } else { | |
| let d = inner(b, a % b, y, x); | |
| *y -= a / b * *x; | |
| d | |
| } | |
| } | |
| let (mut x, mut y) = (T::zero(), T::zero()); | |
| inner(a, b, &mut x, &mut y); | |
| (x, y) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment