Greatest Common Divisor

Using Euclid's Algorithm, we find the GCD.

Runtime: O(log N), where N is the magnitude of the smaller of the two numbers.

Very useful for reducing fractions.

Java
Here are two versions. The first is recursive, and the second is iterative. public static int gcd(int a, int b) { if(b == 0) return a;    return gcd(b, a%b); } public static int gcd(int a, int b) { while(b != 0) {        int t = b; 	b = a % b; 	a = t;     } return a; }

Here is the extended Euclidean algorithm. Returns x and y such that ax + by = gcd(a, b). static int x, y; public static int exgcd(int a, int b) { int ox = 1; int oy = 0; int nx = 0; int ny = 1; boolean swap = false; if(a < b)    { int tmp = a;        a = b;         b = tmp; swap = true; }    while(b > 0) {        int q = a / b;         int m = a % b;         a = b; b = m;         int nnx = ox - q*nx; int nny = oy - q*ny; ox = nx; nx = nnx; oy = ny; ny = nny; }    x = (swap? oy : ox); y = (swap? ox : oy); return a; }