better document GCD programs

This commit is contained in:
Krishna Vedala 2020-05-27 15:42:12 -04:00
parent a436cd7a1b
commit e31ee6e833
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7
3 changed files with 62 additions and 31 deletions

View File

@ -1,10 +1,17 @@
#include <cmath>
/**
* @file
* @brief Compute the greatest common denominator of two integers using
* *iterative form* of
* [Euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm)
*
* @see gcd_recursive_euclidean.cpp
*/
#include <iostream>
#include <stdexcept>
// will find the greatest common denominator of two ints integers
// Euclidean algorithm can be found here
// https://en.wikipedia.org/wiki/Euclidean_algorithm
/**
* algorithm
*/
int gcd(int num1, int num2) {
if (num1 <= 0 | num2 <= 0) {
throw std::domain_error("Euclidean algorithm domain is for ints > 0");
@ -34,6 +41,9 @@ int gcd(int num1, int num2) {
return previous_remainder;
}
/**
* Main function
*/
int main() {
std::cout << "gcd of 120,7 is " << (gcd(120, 7)) << std::endl;
try {

View File

@ -0,0 +1,48 @@
/**
* @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
*/
#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;
}

View File

@ -1,27 +0,0 @@
// C++ program to find GCD of two numbers
#include <iostream>
// Recursive function to return gcd of a and b
int gcd(int a, int b) {
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver program to test above function
int main() {
int a = 98, b = 56;
std::cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
return 0;
}