费波那契数列的简单实现,这是常见的递归问题,但实现的方法有很多种,当然算法肯定要简单高效的了,网上那些递归算法总觉得不好看,所以我自己就写了下面这个程序,毕竟算法是根据问题出来的,遇到不会的问题还是有自己的想法比较好,特别是算法这方面的。
package test;
import java.text.DecimalFormat;
import java.util.Arrays;
//两种方法打印个数为n的斐波那契数列
public class Fibonacci {
//不借助工具容器的数学计算,当增加的功能越来越多时,简洁性和可读性都会大大降低
// n为需要显示的数列个数 (注:仅显示int值范围类数列,大概能显示45个)
protected void way1(int n) {
int n1 = 1;
int n2 = 1;
int count = 0;
String string = new String(1+"\t"+1+"\t");
if(n == 1) {
System.out.println("1");
}
//可显示n为1开始的任何数的数列
while( count != n/2 -1 ) {
n1 += n2;
string += Integer.toString(n1)+"\t";
n2 += n1;
string += Integer.toString(n2)+"\t";
count ++;
}
if (n%2!=0) {
n1 = n1 + n2;
string += Integer.toString(n1)+"\t";
}
System.out.println(string);
}
//借助数组的迭代实现,有很好的可读性,同时十分简洁,在后续功能增加的情况下也不复杂
//比如这里增加一个功能,求黄金分割率,要用上面的实现的话,那代码就太乱了
protected void way2(int n) {
int[] fbci =new int [n];
double[] goldindex = new double[n-1];
fbci[0] = 1;
fbci[1] = 1;
goldindex[0] = 1.00;
for (int i = 2; i < fbci.length; i++) {
fbci[i] = fbci[i-1] + fbci[i-2];
}
DecimalFormat dFormat = new DecimalFormat("0.000000");//控制小数位数,可取消该功能
String result = new String();
for (int i = 1; i < goldindex.length; i++) {
goldindex [i] = (double)(fbci[i])/(double)(fbci[i+1]);
result += dFormat.format(goldindex [i])+"\t";
}
System.out.println(Arrays.toString(fbci));
System.out.println(result);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Fibonacci a1 = new Fibonacci();
a1.way1(15);
a1.way2(15);
}
}
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
0.500000 0.666667 0.600000 0.625000 0.615385 0.619048 0.617647 0.618182 0.617978 0.618056 0.618026 0.618037 0.618033