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/04-lcm/lcm.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/04-lcm/lcm.cpp')
-rw-r--r-- | 01-algorithmic_toolbox/01-intro/04-lcm/lcm.cpp | 34 |
1 files changed, 31 insertions, 3 deletions
diff --git a/01-algorithmic_toolbox/01-intro/04-lcm/lcm.cpp b/01-algorithmic_toolbox/01-intro/04-lcm/lcm.cpp index c6f503c..62e7799 100644 --- a/01-algorithmic_toolbox/01-intro/04-lcm/lcm.cpp +++ b/01-algorithmic_toolbox/01-intro/04-lcm/lcm.cpp @@ -1,8 +1,36 @@ #include <iostream> -long long lcm(int a, int b) { - //write your code here - return a*b; +long long gcd(int a, int b) +{ + long long d, r; + + if ((a == b) || (a == 0)) + return a; + + if (b == 0) + return b; + + if (b > a) { + d = a; + a = b; + b = d; + } + + for(;;) { + d = a / b; + r = a - (d * b); + if (r == 0) + break; + a = b; + b = r; + } + + return (long long) b; +} + +long long lcm(int a, int b) +{ + return (b / gcd(a, b)) * a; } int main() { |