Compute the greatest common denominator of two integers using recursive form of Euclidean algorithm
More...
#include <iostream>
Go to the source code of this file.
|
int | gcd (int num1, int num2) |
|
int | main () |
|
Compute the greatest common denominator of two integers using recursive form of Euclidean algorithm
- See also
- gcd_iterative_euclidean.cpp, gcd_of_n_numbers.cpp
Definition in file gcd_recursive_euclidean.cpp.
◆ gcd()
int gcd |
( |
int | num1, |
|
|
int | num2 ) |
algorithm
Definition at line 14 of file gcd_recursive_euclidean.cpp.
14 {
15 if (num1 <= 0 | num2 <= 0) {
16 throw std::domain_error("Euclidean algorithm domain is for ints > 0");
17 }
18
19 if (num1 == num2) {
20 return num1;
21 }
22
23
24 if (num1 == 0)
25 return num2;
26 if (num2 == 0)
27 return num1;
28
29
30 if (num1 == num2)
31 return num1;
32
33
34 if (num1 > num2)
35 return gcd(num1 - num2, num2);
36 return gcd(num1, num2 - num1);
37}
int gcd(int num1, int num2)
◆ main()
Main function
Definition at line 42 of file gcd_recursive_euclidean.cpp.
42 {
43 std::cout <<
"gcd of 120,7 is " << (
gcd(120, 7)) << std::endl;
44 try {
45 std::cout <<
"gcd of -120,10 is " <<
gcd(-120, 10) << std::endl;
46 } catch (const std::domain_error &e) {
47 std::cout << "Error handling was successful" << std::endl;
48 }
49 std::cout <<
"gcd of 312,221 is " << (
gcd(312, 221)) << std::endl;
50 std::cout <<
"gcd of 289,204 is " << (
gcd(289, 204)) << std::endl;
51 return 0;
52}