F (n) =f (n-1) +f (n-2)
1. Iterative implementation, O (2 of the n-th square)
1 /**2 * Fibonacci Iterative implementations3 * @paramN4 * @return5 */6 Public intFabonacci_1 (intN) {7 if(n<0)return0;8 if(n==1| | n==2)return1;9 returnFabonacci_1 (n-1) +fabonacci_1 (n-2);Ten}
2. Recursive implementation, O (N)
1 /**2 * Fibonacci Recursive implementations3 * @paramN4 * @return5 */6 Public intFabonacci_2 (intN) {7 if(n<0)return0;8 if(n==1| | n==2)return1;9 intres = 1,pre=1,temp=0;Ten for(inti=3;i<=n;i++){ Onetemp =Res; Ares = res+Pre; -Pre =temp; - } the returnRes; -}
3. Using the second-order matrix implementation, O (LOGN)
1 /**2 * Fibonacci Ponachi Matrix Implementation3 * @paramN4 * @return5 */6 Public intFabonacci_3 (intN) {7 if(n<0)return0;8 if(n==1| | n==2)return1;9 int[] base={{1,1},{1,0}};Ten int[] res = Matrixpower (base, n-2); One returnRes[0][0]+res[1][0]; A } - - //using a second-order matrix to find the Fibonacci the - Public int[] Matrixpower (int[] m,intp) { - int[] res =New int[M.length] [M[0].length]; - //set res as the unit matrix + for(inti=0;i<res.length;i++){ -Res[i][i]=1; + } A at int[] temp =m; - for(;p!=0;p>>=1){ - if((p&1)!=0){ - Mulimatrix (res, temp); - } - Mulimatrix (temp, temp); in - } to returnRes; + } - the * //2 multiplication of matrices $ Public int[] Mulimatrix (int[] M1,int[] m2) {Panax Notoginseng int[] res =New int[M1.length] [M2[0].length]; - for(inti=0;i<m1.length;i++){ the for(intj=0;j<m2[0].length;j++){ + for(intk=0;k<m2.length;k++){ ARES[I][J] + = m1[i][k]*M2[k][j]; the } + } - } $ returnRes; $}
Fibonacci Issues (Java)