Answer to Question #181423 in C++ for Darren

Question #181423

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 passed an argument that is not positive (i.e., less than zero), then the function should return the value 0 as a sentinel value to indicate that an error occurred. Thus, for example:

cout << g_c_d(40,50) << endl;     // will print 10

cout << g_c_d(256,625) << endl; // will print 1

cout << g_c_d(42,6) << endl;      // will print 6

cout << g_c_d(0,32) << endl;     // will print 0

cout << g_c_d(10,-6) << endl;   // will print 0

1
Expert's answer
2021-04-18T07:16:28-0400
#include <iostream>
using std::cout;
using std::endl;

int g_c_d(int n ,int m) 
{
if (n<=0 || m<=0)
    {
       return 0;
    }
while (n != m) 
{
    if (n > m)
    {
        n = n - m;
    }
    else
    {
        m = m - n;
    }
}
return n;
}

int main()
{
    // test example
    cout << g_c_d(40, 50) << endl;     // will print 10
    cout << g_c_d(256, 625) << endl; // will print 1
    cout << g_c_d(42, 6) << endl;      // will print 6
    cout << g_c_d(0, 32) << endl;     // will print 0
    cout << g_c_d(10, -6) << endl;   // will print 0
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS