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.
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.