Fibonacci Issues (Java)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.