Extended Euclidean algorithm
From Elliptic Curve Crypto
The objective of the Extended Euclidean algorithm is to compute the greatest common denominator of two natural numbers and solve the Diophantine equation known as Bézout’s identity. Here is a naïve C++ implementation of pseudocode found on Wikipedia.
#include <iostream>
#include <cassert>
int main(int argc, char **argv) {
long int a,b,q,r0,r1,r,s0=1,s1,s=0,t0=0,t1,t=1;
std::cout << "Enter two integers: ";
std::cin >> a >> b; assert(a > 0 && b > 0);
r0=a; r=b;
while(r>0) {
q=r0/r;
r1=r0-q*r; r0=r; r=r1;
s1=s0-q*s; s0=s; s=s1;
t1=t0-q*t; t0=t; t=t1;
}
std::cout
<< "Bézout coefficients: " << s0 << ", " << t0 << std::endl
<< "greatest common divisor: " << r0 << std::endl
<< "quotients by the gcd: " << t << ", "<< s << std::endl;
return 0;
}