Reputation: 45
I have values x = 10 and y = 6. Then, i have this addxy function to calculate the sum of two numbers. I did my best in this add and now im working on how to construct it to get a product.... ive been wracking my brain for quite a day now but i still cant get it....
public static int addxy(int a, int b)
{
if (b==0)
return a;
else
if (b>0)
return 1 + addxy(a,b-1);
else
if (a==0)
return b;
else
return 1 + addxy(a-1,b);
}
any help will be appreciated
Upvotes: 0
Views: 800
Reputation: 13985
public static int mulxy( int a, int b ) {
if ( b == 0 || a == 0 ) {
return 0;
}
// We need to solve the sign problem.
int signA = ( a > 0) ? 1 : -1;
int signB = ( b > 0 )? 1 : -1;
// now we know the sign of result.
int signResult = signA * signB;
// we don't need sign anymore
int posA = a * signA;
int posB = b * signB;
return signResult * mulPosAB( posA, posB );
}
public int multPosAB( int a, int b ) {
// here we already know that a and b not -tive.
if( a == 0 || b == 0 ) return 0;
// return a + mulPosAB( a, b - 1 );
// or using newAddXY
return newAddXY( a, mulPosAB( a, b - 1 ) );
}
Also your addxy
won't work for cases where both a and b are negative.
public int newAddXY( int a, int b ) {
if( b == 0 ) return a;
if( a == 0 ) return b;
// We need to solve the sign problem.
int signA = ( a > 0) ? 1 : -1;
int signB = ( b > 0 )? 1 : -1;
//return signB + newAddXY( a, b - signB );
// I think we should ensure we re not adding numbers bigger than 1.
// so this will be better
return newAddXY( signB, newADDXY( a, b-signB ) );
}
Upvotes: 0
Reputation: 36304
If you want to have x*y
then You have to recursively add x
, y times
like this :
public class Sample {
public static void main(String[] args) {
System.out.println(add(5, 6));
System.out.println(add(-5, 6));
System.out.println(add(5, -6));
System.out.println(add(-5, -6));
}
static int add(int x, int y) {
if (x==0 ||y == 0) {
return 0;
}
if (y > 0)
return x + add(x, y - 1); //for positive numbers
else
return -x + add(x, y + 1); // for negative numbers
}
}
O/P :
30
-30
-30
30
Upvotes: 2
Reputation: 10417
I guess you want something like this, right?
public static int multiply(int a, int b)
{
if (a == 0 || b == 0)
return 0;
if (a < 0)
return -multiply(-a, b);
if (b < 0)
return -multiply(a, -b);
return multiply(a, b - 1) + a;
}
Upvotes: 3