Home > Enterprise >  prevent an infinite loop in a production system(Js Code Test question)
prevent an infinite loop in a production system(Js Code Test question)

Time:12-08

Please understand the following program:

function recur(n, cur) {
  if (!cur) {
    cur = 0;
  }
  if (n < 2) {
    throw new Error('Invalid input');
  }
  if (n === 2) {
    return 1 / n   cur;
  }
  return recur(n - 1, cur   1 / (n * (n - 1)));
}

To prevent an infinite loop in a production system. Write a program doing the same calculation without recursion. Please be reminded that a while loop is also considered not good in a production system.

I don't quite understand what the original CODE is supposed to do :(

CodePudding user response:

here is your function without recursive.

function nonRecur(n, cur) {
    if (!cur) {
        cur = 0;
    }
    if (n < 2) {
        throw new Error('Invalid input');
    }
    for (; n > 1; --n){
        if (n === 2) {
            cur = 1 / n   cur;
            break;
        }
        cur = cur   1 / (n * (n - 1));
    }
    return cur
}

CodePudding user response:

you can try below code for the same

function recur(n, cur) {
 if (!cur) {
  cur = 0;
 }
 if (n < 2) {
  throw new Error('Invalid input');
 }
 for(var i = n; i > 2; i--){
    cur = cur 1/(i * (i -1));
 }
 return 1 / i   cur;
}

CodePudding user response:

To prevent an infinite loop in the above program, we can use a for loop instead of recursion to perform the same calculation. Here is an example of how this can be done:

function calculate(n) {
  let cur = 0;

  // Check for invalid input
  if (n < 2) {
    throw new Error('Invalid input');
  }

  // Perform the calculation using a for loop
  for (let i = 2; i <= n; i  ) {
    cur  = 1 / (i * (i - 1));
  }

  return cur;
}

This approach avoids the use of recursion and the potential for an infinite loop. It also ensures that the calculation will not run indefinitely, as the for loop will only run a fixed number of times based on the value of n.

  • Related