简体   繁体   中英

Simple Recursion confusion | Javascript

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.

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

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

Talking about the recursive approach. The function

function multiply(arr, n)

has the job to multiply the first n elements of the array (starting from index 0 to index n-1)

When you call

multiply(arr, n-1)

it will return you the product of first n-1 elements of the array (starting from index 0 to index n-2)

now you have the product of all numbers in the array except the last element that is arr[n-1]

what you do now is use that answer and multiply the element arr[n-1] to it, which basically looks like this

multiply(arr, n - 1) * arr[n - 1];

it can also be written as below

small_answer = multiply(arr, n - 1)
complete_answer = small_answer*arr[n-1]
return complete_answer

now your complete_answer variable will have the product of n elements of the array, and it will return that as the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM