Write code for Fibonacci algorithm (iterative or recursive) and explain what's the performance.
Anonymous
Recursive: void fib(int k) { if(k==0) return 0; if(k==1) return 1; return fib(k-1)+fib(k-2); } Iterative: void fib(int k) { if(k==0) return 0; if(k==1) return 1; int pre2Term =0; int preTerm =1; int retVal = 0; for(int i=2 ; i<=k;i++) { retVal += preTerm + pre2Term; pre2Term = preTerm; preTerm = retVal; } return retVal; } Test: fibTest() { int testInt = 3; print(fib(testInt)); } Iterative version of course has better performance because it doesn't need multiple function calls and program stacks to save variables.
Check out your Company Bowl for anonymous work chats.