Have I been asked to write a fiber function in the most efficient way?
This is the implementation I provided:
public static int fib(int n) { int prev1 = 1, prev2 = 1, ans = 1, i = 3; while (i <= n) { ans = prev1 + prev2; prev1 = prev2; prev2 = ans; i++; } return ans; }
Is this the most effective? What is a large order?
I was also asked to give a large notation of recursive implementation:
public static int recursiveFib(int n) { if (n <= 2) return 1; else return recursiveFib(n-1) + recursiveFib(n - 2); }
I think this is exponential 2 ^ n, so it is inefficient.
source share