Skip to content

Instantly share code, notes, and snippets.

@BrianMacIntosh
Last active December 29, 2015 07:19
Show Gist options
  • Save BrianMacIntosh/7634839 to your computer and use it in GitHub Desktop.
Save BrianMacIntosh/7634839 to your computer and use it in GitHub Desktop.
Calculate the GCD (greatest common denominator) of two integers using the Euclidean algorithm. Recursive or iterative functions.
//Helper fn
int pgcdr(int a, int b)
{
if (a) return pgcdr(b % a, a);
else return b;
}
//Recursive gcd fn
int gcdr(int a, int b)
{
if (!a) return 0;
if (a < 0) a = -a;
return pgcdr((b<0?-b:b) % a, a);
}
//Non-recursive gcd fn
int gcd(int a, int b)
{
if (a < 0) a = -a;
if (b < 0) b = -b;
int al = a;
while (a)
{
al = a;
a = b % a;
b = al;
}
return al;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment