439,317 views
31 votes
31 votes
Write a C++ function using recursion that returns the Greatest Common Divisor of two integers. The greatest common divisor (gcd) of two integers, which are not zero, is the largest positive integer that divides each of the integers. For example, the god of 8 and 12 is 4.

User Njthoma
by
3.0k points

1 Answer

20 votes
20 votes

Answer:

The function is as follows:

int gcd(int num1, int num2){

if (num2 != 0){

return gcd(num2, num1 % num2);}

else {

return num1;}

}

Step-by-step explanation:

This defines the function

int gcd(int num1, int num2){

This is repeated while num2 is not 2

if (num2 != 0){

This calls the function recursively

return gcd(num2, num1 % num2);}

When num2 is 0

else {

This returns the num1 as the gcd

return num1;}

}

User Kumar Akarsh
by
3.2k points