Tail recursive method to multiple 2 numbers
public static int Multiply2(int x, int y)
{
return MulTail(x, y, x);
}
public static int MulTail(int x, int y, int result)
{
if (y == 0 || x == 0)
return 0;
if (y == 1)
return result;
return MulTail(x, y - 1, result+x);
}
Changed the implementation to accommodate negative numbers
public static int Multiply2(int x, int y)
{
if ((y < 0 && x > 0) || (x < 0 && y < 0))
{
y = y - y - y;
x = x - x - x;
}
return MulTail(x, y, x);
}
public static int MulTail(int x, int y, int result)
{
if (y == 0 || x == 0)
return 0;
if (y == 1)
return result;
return MulTail(x, y - 1, result+x);
}