Answer the question
In order to leave comments, you need to log in
About recursion. Why an exception?
krch I have an array. I need to find recursively the products of its factors. by bisecting the array. but recursive calls must stop if the piece of the array we are working with consists of one or two elements.
int recursion(int* X, int N, int i, FILE* res)
{
if (N - i == 2)
return X[i] * X[i+1];
if (N - i == 1)
return X[i];
int N1 = N/2;
int i2 = N - N1 + 1;
return (recursion(X, N1, i, res)*recursion(X, N, i2, res));
}
Answer the question
In order to leave comments, you need to log in
In your implementation of the function, there are a lot of extra elements that greatly complicate the code.
For example FILE* res
, you do not need it at all. You can opt out as well
.
In fact, you only need a pointer to the first element and the number of elements in the array.i
int recursion(int* x, int n)
{
if(n > 2) {
return recursion(x, n/2) * recursion(x + n/2, n - n/2);
} else if(n ==2) {
return x[0] * x[1];
} else {
return x[0];
}
}
n - n/2
is used because integer division and rounding occurs.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question