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

#### Veronica

##### Coder
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.
Code:
``````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.

Poor style.

Remember structured programming? The idea of code blocks. Start at the top, finish at the bottom.

Jumping out of a function from inside a for loop, madness. ;-)

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.

• ChaoticSalmon
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:

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

• Veronica