I tried Binary multiplication technique on decimal numbers.
Algorithm:
To multiply two decimal numbers x and y, write them next to each
other, as in the example below. Then repeat the following: divide the first number by 2,
rounding down the result (that is, dropping the :5 if the number was odd), and double the
second number. Keep going till the first number gets down to 1. Then strike out all the rows
in which the first number is even, and add up whatever remains in the second column.
11 13
5 26
2 52
1 104
……..
143 (answer)
Code:
class Multiply
{
static int temp;
static int sum;
public static void main(String[] args)
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int ans = multiply(x , y);
System.out.println(ans);
}
public static int multiply(int x, int y)
{
if(x==1)
{
System.out.println(x+" : "+y);
return y;
}
temp = multiply(x/2, y*2);
if(x%2==0)
{
System.out.println(x+" : "+y);
return temp;
}
else
{
System.out.println(x+" : "+y);
sum = sum+temp;
return sum;
}
}
}
Something is wrong with the recursion i think but i couldn’t find what it is!!
Your recursion should be like this –