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