Learn AP Comp Sci

Problem of the Day

Problem:

Consider the following recursive method.

/**
* PRECONDITION: m is positive, and n >= 0
*/
public static int helper(int m, int n)
{
if (n == 0)
return 1;
else
return m * helper(m, n - 1);
}

Which of the following operations does the method helper implement?

  1. calculating a power, mn
  2. integer division, m / n
  3. integer division, m % n
  4. integer multiplication, m * n

Show solution:

The correct answer is a. Successive calls to the method helper are made with decreasing values of n, with each call returning the product of m with the results of all future calls of helper.