Blame rate-lav/gcd.h

Packit Service cd2a00
/*
Packit Service cd2a00
 * Fast implementation of greatest common divisor using the binary algorithm.
Packit Service cd2a00
 * Copyright (c) 2007 Nicholas Kain
Packit Service cd2a00
 *
Packit Service cd2a00
 * Permission is hereby granted, free of charge, to any person obtaining a copy
Packit Service cd2a00
 * of this software and associated documentation files (the "Software"), to
Packit Service cd2a00
 * deal in the Software without restriction, including without limitation the
Packit Service cd2a00
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
Packit Service cd2a00
 * sell copies of the Software, and to permit persons to whom the Software is
Packit Service cd2a00
 * furnished to do so, subject to the following conditions:
Packit Service cd2a00
 *
Packit Service cd2a00
 * The above copyright notice and this permission notice shall be included in
Packit Service cd2a00
 * all copies or substantial portions of the Software.
Packit Service cd2a00
 *
Packit Service cd2a00
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Packit Service cd2a00
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Packit Service cd2a00
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Packit Service cd2a00
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
Packit Service cd2a00
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
Packit Service cd2a00
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
Packit Service cd2a00
 * IN THE SOFTWARE.
Packit Service cd2a00
 */
Packit Service cd2a00
Packit Service cd2a00
/* computes gcd using binary algorithm */
Packit Service cd2a00
static int gcd(int a, int b)
Packit Service cd2a00
{
Packit Service cd2a00
	int s,d;
Packit Service cd2a00
Packit Service cd2a00
	if (!a || !b)
Packit Service cd2a00
		return a | b;
Packit Service cd2a00
Packit Service cd2a00
	for (s=0; ((a|b)&1) == 0; ++s) {
Packit Service cd2a00
		a >>= 1;
Packit Service cd2a00
		b >>= 1;
Packit Service cd2a00
	}
Packit Service cd2a00
Packit Service cd2a00
	while ((a&1) == 0)
Packit Service cd2a00
		a >>= 1;
Packit Service cd2a00
	
Packit Service cd2a00
	do {
Packit Service cd2a00
		while ((b&1) == 0) {
Packit Service cd2a00
			b >>= 1;
Packit Service cd2a00
		}
Packit Service cd2a00
		if (a
Packit Service cd2a00
			b -= a;
Packit Service cd2a00
		} else {
Packit Service cd2a00
			d = a-b;
Packit Service cd2a00
			a = b;
Packit Service cd2a00
			b = d;
Packit Service cd2a00
		}
Packit Service cd2a00
		b >>= 1;
Packit Service cd2a00
	} while (b);
Packit Service cd2a00
Packit Service cd2a00
	return a << s;
Packit Service cd2a00
}
Packit Service cd2a00