So, I have this task:
Where n is a positive integer, the function f(n) satisfies the following
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2) when n > 1
- Please create a program to find f(n)
Use the program to find f(8181)
const f = (n) => { if(n === 0) { return 0 } else if(n === 1) { return 1 } else if(n > 1) { return f(n-1) + f(n-2) } else { return null } }
above is the code that i have wrote but it only do just fine when i do n < 40, it starts to slow down when n > 41. it takes forever to load f(100) let alone f(8181)
so, is there any way to optimized this code to meet all the requirements?
thank you in advance!
ps: it's not a school task so i dont have anyone to consult
n>2,f(n-1)will involve callingf(n-2), so you're doing twice as much work as needed for each iteration step. What should be anO(n)operation is becomingO(2^n)!!const f = (src=>(n) => {while(src.length <= n) src[src.length] = src[src.length-1] + src[src.length-2]; return src[n];})([0,1]);uses dynamic programming, not recursion - however, it is important to note thatf(79) > Number.MAX_SAFE_INTEGER- forn>=79you will get approximate values.f(8181)returnsInfinity.f(8181)is a 1,710-digit number - who assigned this insane task to you?