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 ~
returntherecursiveFunction(bigNumber - smallNumber, smallNumber), for the conditionbigNumber > smallSumberand the base case will be to check thesmallNumber == bigNumberorsmallNumber == 0, or something like that. - Usually when the
recursive casehave only one pararmeter/condition like this: ⏩return mod(dividend-divisor, divisor);, here, whatever value is returned in thebase casebecomes the final answer, becauserecursive casedon't make any changes to retuned ans from thebase case.. This is not applicable whenrecursive casehas 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;
}