The definitions of GCD and LCM are well-known, (and taught in middle school I think) I will skip the definitions.
Also, sinceNow, how do we calculate the GCD of two numbers?
A naive solution would be iterating over all positive integers no more than
This will get the GCD in
We can calculate the GCD of
This algorithm uses the easy-to-prove fact
We can now use the following code.
#include <iostream> using namespace std; int gcd(int u, int v) { return u%v==0?v:gcd(v,u%v); } int main(void) { int x, y; cin>>x>>y; cout<<gcd(x,y); }
How do we prove that this algorithm is
Then, we go to
Therefore, the product of two numbers in the function decreases by half every time. Done!
Here's a challenge. Can we find the numbers
There exists infinitely many pairs - this is Bezout's Lemma. The algorithm to generate such pairs is called Extended Euclidean Algorithm.
Comments
Post a Comment