I was asked to write a fib function in the most efficient manner?
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 efficient? What is the big-o order?
I was also asked to give the big-o notation of a recursive implementation:
public static int recursiveFib(int n)
{
if (n <= 2)
return 1;
else
return recursiveFib(n-1) + recursiveFib(n - 2);
}
I think this one is exponential 2^n which is why it's inefficient.