By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ How to calculate the greatest common divisor of two numbers in C++.


We can traverse over all the numbers from min(A, B) to 1 and check if the current number divides both A and B or not. If it does, then it will be the GCD of A and B.
int GCD(int A, int B) {
    int m = min(A, B), gcd;
    for(int i = m; i > 0; --i)
        if(A % i == 0 && B % i == 0) {
            gcd = i;
            return gcd;

I am a beginner in c++ programming and I am stuck on the problem of finding the GCD (greatest common divisor) of two non-negative integers, a and b. I have taken a code reference from a post related to this problem. Could you please let me know if the code is correct?
Why would that code not be correct ? Are you running into a problem with it ? Or don't you trust that site ?
And what do you mean you are "stuck" ? You'll have to show what you've done, and explain how it failed or why you cannot proceed. Being a beginner does not excuse you from giving it your best shot.
Jumping out of a function from inside a for loop, madness. ;-)
Question of taste, methinks. The return will end the loop as surely as a break would. If you find you're done you may as well quit the function there and then.
But if there's any technical reason not to do this (rather than an ethical reason) I would like to hear.
I dont see anything wrong i your code, except if you try to find the greatest you should loop from top to down. Or im i too tired here to understand something? 😀

I think it was C++ 11 where was __gdc introduced. Then its basically like this:

int a = 24, b = 36;
int gcd = __gcd(a, b);
cout << "Greatest common divider of " << a << " and " << b << " is " << gcd << endl;

New Threads

Buy us a coffee!

Top Bottom