Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda