Recursion tricks
caution
These are just some guesswork and observations by Sarthak, These are by no means Guaranteed
Divisivility / mod - %
related
If you would have solved that problem using %
modulo / remainder / division related than MAYBE I can TRY this 👇
- for checking for divisibility,the recursive case will be ~
return
therecursiveFunction(bigNumber - smallNumber, smallNumber)
, for the conditionbigNumber > smallSumber
and the base case will be to check thesmallNumber == bigNumber
orsmallNumber == 0
, or something like that. - Usually when the
recursive case
have only one pararmeter/condition like this: ⏩return mod(dividend-divisor, divisor);
, here, whatever value is returned in thebase case
becomes the final answer, becauserecursive case
don't make any changes to retuned ans from thebase case
.. This is not applicable whenrecursive case
has many parameters or conditions like this: ⏩return (fibonacci(n-1) + fibonacci(n-2));
#include <iostream>
using namespace std;
int mod(int dividend,int divisor)
{
// making sure there is no divison by zero
if (divisor==0)
{
cout << "Divisor cannot be 0";
return 0;
}
// base condition
if (dividend < divisor)
{
return dividend;
}
// recursive code
else
{
return mod(dividend-divisor, divisor);
}
}
int main() {
int a=32;
int b=6;
cout <<a<<" mod "<<b<< " = "<<mod(a,b);
return 0;
}