Search code examples
crecursionmathexponent

Power function by means of recursion


The implementation should compute a number to the nth power using recursion, however, every call to itself, keeps "nb" unchanged, while power decrements. I've tried using a accumulator variable but this reinitializes to default with every repeated call. Is there a way to save nb * nb to nb, without adding an extra parameter? or losing the base value?

When I run ft_recursive_power(3, 10); in a c visualizer (ctutor) and pass it these arguments, it displays that nb remains 3 throughout the execution, and returns 177147, while it should accumulate the multiplication and return 59049. Or am I missing something?

int   ft_recursive_power(int nb, int power)
{
  // 0 to the 0th case
  if (power == 0 && nb == 0)
    return (1);
  // recursive case
  if (power > 0)
    return (nb * ft_recursive_power(nb, power - 1));
  return (nb);
}

Solution

  • You're getting an incorrect result because your base case is wrong.

    The value 177147 is 311 as opposed to 310, which means you're multiplying one extra time. That happens because you return nb in the base case when power is 0.

    When raising a number to the 0 power the result is 1, so your base case should be 1.

    int   ft_recursive_power(int nb, int power)
    {
      // 0 to the 0th case
      if (power == 0 && nb == 0)
        return 1;
      // recursive case
      if (power > 0)
        return nb * ft_recursive_power(nb, power - 1);
      return 1;
    }