Sunday, July 30, 2017

Write a function named "g_c_d" that takes two positive integer arguments and returns as its value the greatest common divisor of those two integers. If the function is passed an argument that is not positive (i.e., greater than zero), then the function should return the value 0 as a sentinel value to indicate that an error occurred.

/*
For more exercises and lessons, visit http://shegertech.blogspot.com/
*/

#include <iostream>
#include <cstdlib>
using namespace std;

int g_c_d (int a, int b)
{
if (a <= 0 || b <= 0) // a parameter is not positive
return 0; // exit and return the error sentinel
int trial_divisor;
trial_divisor = ( a <= b ? a : b ); // set it to the smaller
while (a % trial_divisor != 0 || b % trial_divisor != 0)
--trial_divisor;
return trial_divisor;
}

int main(){
int n1=12, n2=30;
cout<<g_c_d(n1, n2)<<endl;
system("pause");
return EXIT_SUCCESS;
}

Share: