Another One For Interview … This Time Recursion

Recursion has been famous technique of eliminating loop and breaking the execution of code into regular call of methods.
Some times your interview is going good and there comes recursion which just shocks you….
It is simple but it’s simplicity makes you in trouble especially during strict time bound interview.
Basically recursion is a technique of calling a method from it’s own method.
It is similar to divide and break the complex logic into simple executable code.
Key to remember before starting to code any recursion solution is this equation

F(n)=F(x) + – F(n)

.
Where F(n) calls it self multiple times using the old value.

Let say we have to multiply two positive unknown values without using the multiplication sign.
So the function would
F(0) =b+F(1) —– F(1)=b+F(0) …. and so on ….

So lets write the code.

using System;

public class Test
{
public static void Main()
{
int d= multiply (10,2);
Console.WriteLine(d);
}
public static int multiply(int a,int b)
{
if(b==0)
{
return 0;
}
else
{
return a+multiply(a,b-1);
}
}
}

 

Here you can see the function is calling itself and reusing the old returned value until and unless value becomes 0. We can do factorial and division using the same technique with little bit enhancement.

 

Advertisements