Answer to Question #180890 in C++ for Darren

Question #180890

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 (less than zero), then the function should return the value 0 as a sentinel value to indicate that an error occurred.

         cout << g_c_d(40,50) << endl;  

         cout << g_c_d(256,625) << endl; 

        cout << g_c_d(42,6) << endl;     

        cout << g_c_d(0,32) << endl;     

       cout << g_c_d(10,-6) << endl;   

1
Expert's answer
2021-04-14T16:43:52-0400
#include <iostream>
#include <algorithm> // swap

int g_c_d(int x, int y) {
    if(x < 0 || y < 0) return 0;
    while(x && y) {
        x %= y;
        std::swap(x, y);
    }
    return x + y;
}

int main() {
    using std::cout;
    using std::endl;
    cout << g_c_d(40,50) << endl;  
    cout << g_c_d(256,625) << endl; 
    cout << g_c_d(42,6) << endl;     
    cout << g_c_d(0,32) << endl;     
    cout << g_c_d(10,-6) << endl;   
    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