Posted By


jacktan on 10/20/14

Tagged


Statistics


Viewed 1041 times
Favorited by 0 user(s)

Fibonacci第n项java实现


/ Published in: Java
Save to your folder(s)

考虑到Fibonacci数列增长速度之快,返回值用long类型;如果long类型还不够,下一步考虑使用BigInteger类。

----
//TODO

* 补充两种方法的大O分析和性能测试


Copy this code and paste it in your HTML
  1. /**
  2. * 递归方法求Fibonacci数列(1,1,2,3,5,8……)在第i项的值;
  3. * Fibonacci第n项的递推式为F(n)=F(n-1)+F(n-2) (n>2)。
  4. *
  5. * @param Fibonacci数列的第i项
  6. * @return Fibonacci数列第i项的值;如果i<1,则返回0;
  7. *
  8. */
  9. public static long fibonacci(int i)
  10. {
  11.  
  12. if(i<1)
  13. {
  14. return 0;
  15. }
  16. if(i<3)
  17. {
  18. return 1;
  19. }
  20. long mth_result = fibonacci(i-1) + fibonacci(i-2);
  21.  
  22. return mth_result;
  23. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.