[Solved] How can I convert this JavaScript recursive function to an iterative one? [closed]


You can use a while loop and use the exit condition of your recursion as the exit condition from your while loop

function squirt( n, g ) 
{   
  var d, ng, g = n / 2.0; //initialize g
  while ( g != ( d + g ) / 2.0 ) //convert g==ng to this
  {
     d = n / g; 
     g = ( d + g ) / 2.0;     
  }

  return g; //return g
}

Demo

function squirt( n, g ) 
{   
  var d, ng, g = n/2.0;
  while ( g != ( d + g ) / 2.0 )
  {
     d = n / g; 
     g = ( d + g ) / 2.0;     
  }
  return g;
}

console.log( squirt(4) );
console.log( squirt(5) );
console.log( squirt(6) );
console.log( squirt(7) );
console.log( squirt(8) );
console.log( squirt(9) );
console.log( squirt(10) );

7

solved How can I convert this JavaScript recursive function to an iterative one? [closed]