Solution Review 1: Find the Greatest Common Divisor
This lesson provides a detailed review of the solution to the challenge in the previous lesson.
We'll cover the following...
Solution
Press + to interact
#include <iostream>using namespace std;int gcd(int num1, int num2){// base caseif (num1==num2){return num1;}//recursive caseif(num1 > num2){gcd(num1-num2, num2);}else if(num2 > num1){gcd(num1, num2-num1);}}int main(){int x=42;int y=56;// computing gcd and storing it in resultint result= gcd(42,56);// printing resultcout<<"Greatest Common Divisor of "<<x<<" and "<<y<<" is "<<result;return 0;}
Understanding the Code
In the code above, the function gcd
is a recursive function as it makes a recursive call in the function body. Below is an explanation of the above code:
Driver Function
-
In the
main()
code, we have defined three integer variables:x
,y
andresult
. -
result
stores the greatest common divisor ofx
andy
when thegcd
function is called. -
line 30 ...