|
例(1):f(x) = f(x-1) + f(x-3), f(x) = 10 (x < 3)例(2):f(x) = ( f(x-1) + f(x-3) + x) / f(x-2), f(x) = 10 (x < 3)
用一个长度为3的数组保存中间结果。move 方法主要用来移动中间结果数组里面的中间结果。
其实完全可以用一个 queue 队列来保存中间结果。直接把用过的 queue head 丢弃,把后面的结果加在队尾。
程序:
[pre]public class Fib{ public static void main(String args[]){ Fib f=new Fib(); for(int i=3;i<=10;i++) System.out.println(f.fibonacci(i)); System.out.println("--------------"); for(int i=3;i<=30;i++) System.out.println(f.f(i)); } public int fibonacci(int x){ if(x< 3) return 10; int[] middleResults={10,10,10}; int result=0; for(int i=1;i<=x-2;i++){ result=middleResults[0]+middleResults[2]; move(middleResults); middleResults[2]=result; } return result;} public double f(int x){ if(x < 3) return 10.0; double[] middleResults ={10.0,10.0,10.0}; double result = 0; for(int i = 1; i <= x-2; i++){ result = (middleResults[2] + middleResults[0] + x) / middleResults[1]; move(middleResults); middleResults[2] = result; } return result; } public void move(int[] array){ int k=array.length; int limit=k-1; for(int i=0;i< limit;i++){ array=array[i+1]; }}public void move(double[]array){ int k=array.length; int limit=k-1; for(int i=0;i< limit;i++){ array=array[i+1]; }}}运行:[/pre]
C:\java>java Fib
20
30
40
60
90
130
190
280
--------------
2.3
1.64
6.7
8.316790736145574
2.485126930312088
2.058052812596989
7.299871825955862
8.881460828008004
2.965189324630314
2.506631991029014
7.762915612937961
9.219500907735743
3.409792287693365
2.951195116656821
8.124818953946315
9.435000886298152
3.83677362970048
3.393885906525632
8.415685316489553
9.580029076521782
4.25419933108847
3.835597071948546
8.654642316160107
9.681740827980857
4.6660206882746005
4.276746659493159
8.854480824055553
9.755429592436586 |
|