next up previous
Next: Comparison between recursion and Up: Unit 11 Previous: Example: recursive implementation of

Example: recursive implementation of the power between two integers

We exploit the following recursive definition of the power between two non-negative integers:

power(b, e) = $\displaystyle \cases{
1, & if \(e=0\)\cr
\mathit{product}(b, \mathit{power}(b, e-1)), & if \(e>0\)}
$

Implementation (we assume that the method product() is defined in the same class):

public static int power(int b, int e) {
  if (e == 0)
    return 1;
  else
    return (product(b, power(b, e-1)));
}


next up previous
Next: Comparison between recursion and Up: Unit 11 Previous: Example: recursive implementation of