Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
how to avoid using recursive function

I found an question and would like to try if I can write a better function without using recursive function and while loop. But I found that I have no idea how to write it better. Is there anyone who can give me some hints or inspire me.

function recursivefunction(i, val) {
  if (!val)  val= 0;
  if (i < 2) throw new Error('wrong input');
  if (i === 2) return 1 / i + val;
 
  return recursivefunction(i - 1, val+ 1 / (i * (i -1)));
}


Write a program doing the same calculation without
recursion. 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

function recursivefunction(i, val) {
  if (!val)  val= 0;
  if (i < 2) throw new Error('wrong input');
  if (i === 2) return 1 / i + val;
 
  return recursivefunction(i - 1, val+ 1 / (i * (i -1)));
}

function nonRecursiveFunction(i, val) {
  if (!val)  val = 0;
  if (i < 2) throw new Error('wrong input');
  while(i > 2) {
    val = val + 1 / (i * (i -1));
    i--;
  }
  return 1 / i + val;
}

const recursive = recursivefunction(4, 2);
const nonrecursive = nonRecursiveFunction(4, 2);

console.log(`Recusrive: ${recursive}, nonrecursive: ${nonrecursive}`);

To be honest, I'd replace the return statement with val + 0.5, because we know that i is exactly 2 and we can use a constant value instead of dividing here.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!