U
U
underprogrammer2019-08-15 17:53:21
C++ / C#
underprogrammer, 2019-08-15 17:53:21

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));
  }

fprintf(res, "%d", recursion(X, N, i, res)); this is how I display the answer
X- array N - initially the length of the array, the
problem is that the visual says that I have an exception under the line int recursion...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Grigory, 2019-08-23
@Griglapidus

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];
    }
}

The division of the array into parts occurs by passing 2 halves of the previous array and their sizes.
Just in case, I'll pay attention. n - n/2is used because integer division and rounding occurs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question