1.6k views
3 votes
Which of the following methods is such that mystery(a, b) = a*b for all non negative integers a and b?

A. B. C. D.
static int mystery(int x, int y)
{ if(y == 0)
return x;
return mystery(x + y, y); }
static int mystery(int x, int y)
{ if(y == 1) return x; return mystery(x + x, y-1); }
static int mystery(int x, int y)
{ if(x == 0) return 0;
return mystery(x-1, y) + y; }

1 Answer

0 votes

Final answer:

The correct implementation of the function mystery(a, b) is the one that uses recursion to add the value of 'b' to itself 'a' times, simulating multiplication.

Step-by-step explanation:

The student is asking for the correct implementation of a function named mystery that multiplies two non-negative integers a and b without directly using the multiplication operator. We need to identify which provided method correctly performs this operation.

The correct method is:

static int mystery(int x, int y) {
if(x == 0) return 0;
return mystery(x-1, y) + y;
}

This method uses recursion to add the number y to itself x times. When x reaches 0 (the base case), the recursion stops and the sum of all the y values added together equals x multiplied by y.

User Niranga Sandaruwan
by
8.1k points

No related questions found