Optimization of the Fibonacci sequence Java algorithm with HashMap

Source: Internet
Author: User

Fibonacci is the first item of 0, the second item is 1, and each subsequent item is a sequence of two items in front.
Source: Fibonacci.java
public class Fibonacci{private static int times=0, public static void Main (String args[]) {  int nums = Fibonacci (+); 
   SYSTEM.OUT.PRINTLN ("Result:" +nums);  System.out.println ("Number of times:" +times); }    static int fibonacci (int n) {times++;if (n<=1) return 1;   Return Fibonacci (n-1) +fibonacci (n-2);   } }
For the 30th term. Called function 2,692,539 times, efficiency and low

The second optimization algorithm is

Using HashMap to record the value of each operation, the results are dynamically programmed to output each time.

The 30th item is called only 59 times.

Source: Hash.java

Import Java.util.hashmap;public class Hash{public static void Main (String args[]) {HashMap m = new HashMap (); int res = FIB ( (m); SYSTEM.OUT.PRINTLN ("Result:" +res); System.out.println ("Number of times:" +times);} private static int times = 0;public static int Fib (int x,hashmap m) {times++;if (M.containskey (x)) return (Integer) m.get (x ); ElseIf (x==0| | x==1) return 1;int temp = Fib (x-1,m) +fib (x-2,m); m.put (x, temp); return temp;}}

Optimization of the Fibonacci sequence Java algorithm with HashMap

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.