Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make a recursive function in JavaScript

I am trying to make a recursive function for this parameters. Function should determine the nth element of the row

a_0 = 1
a_k = k*a_(k-1) + 1/k
k = 1,2,3...

I am trying really hard to do this but i cant get a result. Please help me to do this

I came up with this but it is not a recursive function. I can not do this as a recursive function

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let a = 1
let k = 1
let n = 3
for (let i = 1; i<=n; i++){
    a = i*a + 1/i
}
console.log(a)

>Solution :

Here’s the recursive function you’re looking for, it has two conditions:

  • k == 0 => 1
  • k != 0 => k * fn(k - 1) + 1/k
function fn(k) {
  if(k <= 0) return 1;
  return k * fn(k - 1) + 1/k;
}

console.log(fn(1));
console.log(fn(2));
console.log(fn(3));
console.log(fn(4));

Note: I changed the condition of k == 0 to k <= 0 in the actual function so it won’t stuck in an infinite loop if you pass a negative k

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading