diff options
author | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 20:29:59 +0100 |
---|---|---|
committer | Jérémy Zurcher <jeremy@asynk.ch> | 2016-11-13 20:29:59 +0100 |
commit | 0f13a35dee0df21f4c1a387b50582a958c7bc439 (patch) | |
tree | d5e7e2d59ea9a709b660d94428ea951a80f085ba /01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp | |
parent | 13eab863735725f9a02cd4ae0b1c25725cc27569 (diff) | |
download | coursera-0f13a35dee0df21f4c1a387b50582a958c7bc439.zip coursera-0f13a35dee0df21f4c1a387b50582a958c7bc439.tar.gz |
Algorithms : complete 01-algorithmic_toolbox 01-intro
Diffstat (limited to '01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp')
-rw-r--r-- | 01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp | 35 |
1 files changed, 25 insertions, 10 deletions
diff --git a/01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp b/01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp index f723be2..fc13392 100644 --- a/01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp +++ b/01-algorithmic_toolbox/01-intro/03-gcd/gcd.cpp @@ -1,16 +1,31 @@ #include <iostream> -int gcd(int a, int b) { - //write your code here - int current_gcd = 1; - for (int d = 2; d <= a && d <= b; d++) { - if (a % d == 0 && b % d == 0) { - if (d > current_gcd) { - current_gcd = d; - } +int gcd(int a, int b) +{ + int d, r; + + if ((a == b) || (a == 0)) + return a; + + if (b == 0) + return b; + + if (b > a) { + d = a; + a = b; + b = d; } - } - return current_gcd; + + for(;;) { + d = a / b; + r = a - (d * b); + if (r == 0) + break; + a = b; + b = r; + } + + return b; } int main() { |