Hunter algorithms-non-recursion optimization for the evaluation of the Fibonacci series

Source: Internet
Author: User

First code

Class test {public static void main (string ARGs []) {int n = 45; long time1 = now (); system. out. print ("Maid (" + N + ") =" + maid (n); system. out. println ("cost:" + (now ()-time1); time1 = now (); system. out. print ("Maid (" + N + ") =" + maid (n); system. out. println ("cost:" + (now ()-time1);} public static long now () {return system. currenttimemillis ();} public static long maid (int n) {If (n = 1) return 1; if (n = 2) return 1; return maid (n-1) + maid (n-2);} public static long maid (int n) {long num1 = 1; long num2 = 1; if (n = 1 | n = 2) {return 1 ;}long numn = 0; For (INT I = 3; I <= N; I ++) {numn = num1 + num2; num1 = num2; num2 = numn ;}return numn ;}}

Execution result:

Analysis:

The implementation of Fibonacci is based on recursion and there will be many repeated computations. Every computation is a new kind of computation, and the previous computation results are not fully utilized, resulting in a serious waste.

The implementation of fibonacci2 is based on dynamic planning, with bottom-up and full use of the previous computing results. The performance varies greatly.

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.