Sunday, 23 August 2015

multiply two numbers recursively

public class Multiplication {
 public static int getProduct(int x, int y){
  if (x==0 || y==0)
   return 0;
  else if( y > 0)
   return x + getProduct(x, --y);
  else
   return -getProduct(x, -y);
 }
}


Following is the junit test case.
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class MultiplicationTest {
 @Test
 public void test1() {
  assertTrue(Multiplication.getProduct(5, 4) == 20);
  assertTrue(Multiplication.getProduct(5, -4) == -20);
  assertTrue(Multiplication.getProduct(-5, 4) == -20);
  assertTrue(Multiplication.getProduct(-5, -4) == 20);
  assertTrue(Multiplication.getProduct(5, 0) == 0);
  assertTrue(Multiplication.getProduct(0, 4) == 0);
  assertTrue(Multiplication.getProduct(0, 0) == 00);
 }
}


No comments:

Post a Comment