Fundamental Algorithms Analysis (001)-Fibonacci sequence[斐波那契數列][C++/Java]

Fibonacci sequence

To begin with, we introduce an easy and thoughtful example to feel first. All the programs will be written in C++ or Java.
Here we will illustrate 4 different algorithms to see the pros and cons of algorithms to a specified problem.

Recusive method (C++)

//Recusive method
double Fibonacci(int n)=[]{return n == 1 || n == 2?1:fs2(n - 1) + fs2(n - 2);};

You can try a number under 40, otherwise you will wait for so long.

Improved recusive method(C++)

//Faster than pure recusive method
double* table = new double[99999]();
double Fibonacci(int n) =[]{return table[--n] == 0 ? table[n] = fs1(n) + fs1(n - 1) : table[n];};

Iteration method(C++)

//The best solution both in temporality and spatiality for regular algorithms, exclude formula method.
double Fibonacci(int n) {
	double a=1, b=1,c=0;// a,b previous two state;c currrent state
	for (int i = 3; i <= n; ++i) (c = a + b,a = b,b = c);
	return c;
}

Numerical method(C++)

//This is the most powerful and fastest method.
double Fibonacci(int n)=[] {return floor(pow((1+sqrt(5))/2,n)/sqrt(5)+0.5);};

Main test(C++)

#include <iostream>
using namespace std;
//Recusive method
double fs1(int n)=[]{return n == 1 || n == 2?1:fs2(n - 1) + fs2(n - 2);};
//Improved recusive method
double* table = new double[99999]();
double fs2(int n)=[]{return table[--n] == 0 ? table[n] = fs1(n) + fs1(n - 1) : table[n];};
//Iteration method
double fs3(int n) {
	double a = 1, b = 1, c = 0;// a,b previous two state;c currrent state
	for (int i = 3; i <= n; ++i) (c = a + b, a = b, b = c);
	return c;
}
double fs4(int n)=[] {return floor(pow((1+sqrt(5))/2,n)/sqrt(5)+0.5);};
int main() {
	table[0] = table[1] = 1;
	int n = 10;
	cout << fs4(n);
	delete[] table;
}

If you have more efficient method, welcome to come up.
Following is Java version, if you need, go on please, otherwise stop here.

Main test (Java)

public class Main {
	static double fs1(int n) {
		return n == 1 || n == 2 ? 1 : fs1(n - 1) + fs1(n - 2);
	}
	//Improved recursive method
	static double[] table=new double[99999];
	static double fs2(int n) {
		return table[--n] == 0 ? table[n] = fs2(n) + fs2(n - 1) : table[n];
	}
	//Iteration method
	static double fs3(int n) {
		double a = 1, b = 1, c = 0;// a,b previous two state;c current state
		for (int i = 3; i <= n; ++i) {
			c = a + b;
			a = b;
			b = c;
		}
		return c;
	}
	static double fs4(int n) {
		return Math.floor(Math.pow((1 + Math.sqrt(5)) / 2, n) / Math.sqrt(5) + 0.5);
	}
	public static void main(String[] args) {
		table[0] = table[1] = 1;
		int n = 10;
		System.out.println(fs4(n));
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章