So I'm given an assignment. The question is: Write a recursive function to compute the greatest common divisor (gcd) of two integers.
The gcd of two integers is the largest integer that divides them both.
and the answer to the code is this:
#include <iostream>
#include <string>
usingnamespace std;
int gcd(int mick, int keith)
{
if ( mick % keith == 0)
return keith;
elsereturn gcd(keith, mick % keith);
}
int main()
{
int a, b;
cin >> a >> b ;
cout << gcd(a,b) << endl;
return 0;
}
Can someone please explain in layman terms what does the return gcd (keith, mick % keith) do? I thought you can't return a function back to the same function? When the compiler reads "return gcd(keith, mick % keith);", what exactly is it returning? is it re-entering the integers of keith, remainder of mick % keith back into the function gcd?
It returns the value given by calling itself. Since gcd(int,int) returns a value of type int, it is returning whatever is produced when it calls itself with new parameters.
So, you're not returning the function, but the value that that function returns.