Sunday, 23 August 2015

compute exponent recursively

Write a function that takes base and exponent as input and compute base power input.

Power(2, 4) = 16
Power(3, 5) = 243
Power(-2, 3) = -8
Power(2, -3) = 0.125
public class Exponenet {

 public static double getPower(int a, int x) {
  if (a == 0)
   return 0;
  if (x == 0)
   return 1;

  if (x < 0) {
   return 1 / calcPower(a, -x);
  }
  return calcPower(a, x);
 }

 private static double calcPower(int a, int x) {
  if (x == 1)
   return a;
  return a * calcPower(a, --x);
 }
}


Following is the junit test case.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ExponenetTest {

 @Test
 public void test1(){
  assertTrue(Exponenet.getPower(2, 4) == 16);
  assertTrue(Exponenet.getPower(3, 5) == 243);
  assertTrue(Exponenet.getPower(-2, 3) == -8);
  assertTrue(Exponenet.getPower(2, -3) == 0.125);
  assertTrue(Exponenet.getPower(2, 0) == 1);
  assertTrue(Exponenet.getPower(0, 100) == 0);
 }
}


No comments:

Post a Comment