Consider the following ANSI C function:
int SomeFunction(int x, int y)
{
if ((x == 1) || (y == 1)) return 1;
if (x == y) return x;
if (x > y) return SomeFunction(x - y, y);
if (y > x) return SomeFunction(x, y - x);
} The value returned by SomeFunction(15, 255) is \(\underline{\hspace{2cm}}\).
To solve the problem, we need to understand what the given C function SomeFunction does. Let's break it down:
x==1 or y==1, the function returns 1.x==y, it returns x (or y, since they are equal).x>y, the function is called recursively with (x-y, y). y>x, the recursion occurs with (x, y-x).The function effectively computes the greatest common divisor (GCD) of x and y using a recursive form of the Euclidean algorithm.
Let's apply this to find SomeFunction(15, 255):
x=15, y=255: Since y>x, call SomeFunction(15, 255-15).x=15, y=240: Still y>x, call SomeFunction(15, 240-15).y by 15 each time, until:x=15, y=15: The condition x==y is met, so return 15.Thus, the value returned by SomeFunction(15, 255) is 15.
Finally, the computed value 15 falls within the given range [15, 15].
| Inputs | Trace | Result |
|---|---|---|
| 15, 255 | 15, 240 | → ... → 15, 15 |
def f(a, b):
if (a == 0):
return b
if (a % 2 == 1):
return 2 * f((a - 1) / 2, b)
return b + f(a - 1, b)
print(f(15, 10))
The value printed by the code snippet is 160 (Answer in integer).
Consider the following Python code snippet.
def f(a, b):
if (a == 0):
return b
if (a % 2 == 1):
return 2 * f((a - 1) / 2, b)
return b + f(a - 1, b)
print(f(15, 10))
The value printed by the code snippet is 160 (Answer in integer).