Skip to main content

Recursion tricks

caution

These are just some guesswork and observations by Sarthak, These are by no means Guaranteed

  • for checking for divisibility,the recursive case will be ~ return the recursiveFunction(bigNumber - smallNumber, smallNumber) , for the condition bigNumber > smallSumber and the base case will be to check the smallNumber == bigNumber or smallNumber == 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 the base case becomes the final answer, because recursive case don't make any changes to retuned ans from the base case.. This is not applicable when recursive 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;
}