Last active
December 29, 2015 07:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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