Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Last active January 6, 2022 01:49
Show Gist options
  • Select an option

  • Save MikuroXina/f4205a25d8a0e6411a5fa0a8a46990f5 to your computer and use it in GitHub Desktop.

Select an option

Save MikuroXina/f4205a25d8a0e6411a5fa0a8a46990f5 to your computer and use it in GitHub Desktop.
The implementation of Extended Euclidean algorithm.
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