-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
Copy pathgcd_recursive_euclidean.cpp
52 lines (46 loc) · 1.21 KB
/
gcd_recursive_euclidean.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* @file
* @brief Compute the greatest common denominator of two integers using
* *recursive form* of
* [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm)
*
* @see gcd_iterative_euclidean.cpp, gcd_of_n_numbers.cpp
*/
#include <iostream>
/**
* 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;
}
// Everything divides 0
if (num1 == 0)
return num2;
if (num2 == 0)
return num1;
// base case
if (num1 == num2)
return num1;
// a is greater
if (num1 > num2)
return gcd(num1 - num2, num2);
return gcd(num1, num2 - num1);
}
/**
* Main function
*/
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;
}