H
H
HonestHacker2019-08-15 18:02:03
C++ / C#
HonestHacker, 2019-08-15 18:02:03

What is wrong with this recursion?

there is an array. 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

2 answer(s)
I
Ivan Klimenko, 2019-08-15
@HonestHacker

Correct function:

int mul(int * arr, int N, int shift = 0)
{
    switch (N)
    {
        case 1:
            return arr[shift];
        break;

        case 2:
            return (arr[shift] * arr[shift + 1]);
        break;

        default:
            int M = N / 2;
            return (mul(arr, M, shift) * mul(arr, N - M, shift + M));
    }
}

In your function, the last three lines are always executed, regardless of the length of the array. Therefore, the array is out of bounds.

J
jcmvbkbc, 2019-08-15
@jcmvbkbc

What is wrong with this recursion?

She looks incomprehensible. It can be rewritten like this:
int mul(const int *x, int n)
{
    assert(n > 0);
    if (n == 1)
        return x[0];
    if (n == 2)
        return x[0] * x[1];
    return mul(x, n / 2) * mul(x + n / 2, n - n / 2);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question