Home > Back-end >  Simple Recursion confusion | Javascript
Simple Recursion confusion | Javascript

Time:06-15

Learning Javascript, curious about why this logic pans out correctly?

Specifically why does return multiply(arr, n - 1) * arr[n - 1]; Why does it need to be multiplied by arr[n - 1]

Non Recursive Approach:

function multiply(arr, n) {
    let product = 1;
    for (let i = 0; i < n; i  ) {
      product *= arr[i];
    }
    return product;
  }

Recursive Approach:

function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

Both give the same result, as they should.

CodePudding user response:

The basic recursion logic is to multiply the last number with the product of all the previous numbers. arr[n - 1] is the last number. (arrays are 0-indexed, so n-1 is the last index.)

If we have an array like [3, 5, 7, 9], on the first call it will be like multiply([3,5,7]) * 9

CodePudding user response:

function multiply(arr, n) {
    if (n <= 0) {
      return 1;
    } else {
      return multiply(arr, n - 1) * arr[n - 1];
    }
  }

ok, you want to multiply all or some element of array. i tell you don't multiply all elements, it is complex, first multiply from second element to last, and at last multiply it to first.

you do that:

x0 * x1 * x2 * ... * xn => x0 * (x1 * x2 * ... * xn)

ok, do that again:

x0 * (x1 * x2 * ... * xn) = x0 * (x1 * (x2 * ... * xn)

at every step, you seperate one element and go on...

at the end, you have only one element: xn, so you backtrack it and multiply to xn-1 and you backtrack result and multiply to xn-2 ... and at the end x0

hope to be helpful

  • Related