The large-ordinate of recursive and iterative fiber functions?

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.

+4
source share
3 answers

I would say that the best way to find the fib for a specific n is to use the matrix calculation method, as indicated in Link - Page19

enter image description here

where F0 = 0 and F1 = 1. This matrix relation can easily be used to find fib for any value of n and n + 1. The best part is that the multiplying matrix does not need to be multiplied n times, but only logN times to find the actual multiplier value. Thus, the total replenishment of the algorithm is only O (logN).

The equation is derived from the main relation

F1 = 0 * F0 + 1 * F1

F1 = 1 * F0 + 1 * F2

Iterating over n, the matrix of the multiplier must be multiplied n times.

+3
source

Your implementation of O(n) is the usual way to implement the Fibonacci function. Recursive definition of O(fib(n)) if memoization or the like is not used.

There is also a closed expression for the form of Fibonacci numbers and this link has some implementations of faster functions.

+8
source

Here is the matrix method to complete this page:

 public static void main(String[] args) { int n = 25; matMul(n - 1); System.out.printf("\n%dth Fibonnacci number : %d\n\n", n, M[0][0]); } static int[][] M = {{1,0},{0,1}}; static int[][] A = {{1,1},{1,0}}; static int[][] C = {{0,0},{0,0}}; static void matMul(int n) { if (n > 1) { matMul(n/2); mulM(0); } if (n%2!=0) { mulM(1); } } static void mulM(int m) { int i,j,k; if (m==0) { for (i=0;i<2;i++) for (j=0;j<2;j++) { C[i][j]=0; for (k=0;k<2;k++) C[i][j]+=M[i][k]*M[k][j]; } } else { for (i=0;i<2;i++) for (j=0;j<2;j++) { C[i][j]=0; for (k=0;k<2;k++) C[i][j]+=A[i][k]*M[k][j]; } } for (i=0;i<2;i++) for (j=0;j<2;j++) { M[i][j]=C[i][j]; } } 
+2
source