TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
gcd_iterative_euclidean.cpp File Reference

Compute the greatest common denominator of two integers using iterative form of Euclidean algorithm More...

#include <iostream>
#include <stdexcept>
Include dependency graph for gcd_iterative_euclidean.cpp:

Go to the source code of this file.

Functions

int gcd (int num1, int num2)
 
int main ()
 

Detailed Description

Compute the greatest common denominator of two integers using iterative form of Euclidean algorithm

See also
gcd_recursive_euclidean.cpp, gcd_of_n_numbers.cpp

Definition in file gcd_iterative_euclidean.cpp.

Function Documentation

◆ gcd()

int gcd ( int num1,
int num2 )

algorithm

Definition at line 15 of file gcd_iterative_euclidean.cpp.

15 {
16 if (num1 <= 0 | num2 <= 0) {
17 throw std::domain_error("Euclidean algorithm domain is for ints > 0");
18 }
19
20 if (num1 == num2) {
21 return num1;
22 }
23
24 int base_num = 0;
25 int previous_remainder = 1;
26
27 if (num1 > num2) {
28 base_num = num1;
29 previous_remainder = num2;
30 } else {
31 base_num = num2;
32 previous_remainder = num1;
33 }
34
35 while ((base_num % previous_remainder) != 0) {
36 int old_base = base_num;
37 base_num = previous_remainder;
38 previous_remainder = old_base % previous_remainder;
39 }
40
41 return previous_remainder;
42}

◆ main()

int main ( void )

Main function

Definition at line 47 of file gcd_iterative_euclidean.cpp.

47 {
48 std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl;
49 try {
50 std::cout << "gcd of -120,10 is " << gcd(-120, 10) << std::endl;
51 } catch (const std::domain_error &e) {
52 std::cout << "Error handling was successful" << std::endl;
53 }
54 std::cout << "gcd of 312,221 is " << (gcd(312, 221)) << std::endl;
55 std::cout << "gcd of 289,204 is " << (gcd(289, 204)) << std::endl;
56
57 return 0;
58}
int gcd(int num1, int num2)