From d099d8ee6048f473f48b0c211eeea2338bc7e70e Mon Sep 17 00:00:00 2001 From: cole Date: Sat, 28 Dec 2019 01:10:53 -0500 Subject: [PATCH] feat: add euclidean algorithm implementation of gcd --- math/greatest_common_divisor_euclidean.cpp | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 math/greatest_common_divisor_euclidean.cpp diff --git a/math/greatest_common_divisor_euclidean.cpp b/math/greatest_common_divisor_euclidean.cpp new file mode 100644 index 000000000..c4812e45b --- /dev/null +++ b/math/greatest_common_divisor_euclidean.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +// will find the greatest common denominator of two ints integers +// Euclidean algorithm can be found here +// https://en.wikipedia.org/wiki/Euclidean_algorithm +int gcd(int num1, int num2) { + if (num1 <= 0 | num2 <= 0) { + throw std::domain_error("Euclidean algorithm domain is for ints > 0"); + } + + if (num1 == num2) { + return num1; + } + + int base_num = 0; + int previous_remainder = 1; + + if (num1 > num2) { + base_num = num1; + previous_remainder = num2; + } else { + base_num = num2; + previous_remainder = num1; + } + + while ((base_num % previous_remainder) != 0) { + int old_base = base_num; + base_num = previous_remainder; + previous_remainder = old_base % previous_remainder; + } + + return previous_remainder; +} + +int main() { + std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl; + try { + std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl; + } catch (const std::domain_error &e) { + std::cout << "Error handling was successful" << std::endl; + } + std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl; + std::cout << "gcd of 289,204 is " << (gcd(289, 204)) << std::endl; + + return 0; +}