Finding the Greatest Common Divisor in C#
The greatest common divisor of two numbers is the largest number that divides evenly into both numbers.
The method of calculating this is is to use repeated division and subtraction.
Given two numbers a and b, the first step is to repeatedly divide both numbers by 2 as long as both are even, keeping count of the number of iterations as d.
Now, we loop again while a is not equal to b. If either of the numbers are even we divide the number by 2, without incrementing d in this case. If both numbers are odd, we then replace the bigger of a or b with the difference of the two numbers divided by 2.
Eventually the two numbers will be equal and the loop exits.
Now at this point the greatest common divisor is given by gcd = a (or b) * 2d
The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib
Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009
Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library