有如下整数:
初始数据:a=1,b=1
c=a+b=2;
c=2; d=c+b=3;
c=2; d=3; e=c+d=5
c=2; d=3; e=5; f=d+e=8;
................................
他们组成如下有规律的数列:
2 3 5 8 13 21 34 55
要求打印该规律数列50个来测试for循环和递归的效率:
public class TestDG {
public static void main(String[] args) {
// 2 3 5 8 13 21 34 55
int a = 1;
int b = 1;
int sum = 0;
long startTime = System.currentTimeMillis();
for ( int i = 0; i < 50; i++) {
sum = a + b;
System.out.print(" "+sum);
a = b;
b = sum;
}
long endTime = System.currentTimeMillis();
System.out.println();
System.out.println("for循环算法时间"+(endTime - startTime)+"ms");
startTime = System.currentTimeMillis();
for ( int i = 1; i < 50; i++) {
System.out.print(" "+digui(i));
}
endTime = System.currentTimeMillis();
System.out.println();
System.out.println("递归算法时间"+(endTime - startTime)+"ms");
}
public static int digui(int index){
if( index == 1 ) return 2;
if( index == 2 ) return 3;
return digui(index-1) + digui(index-2);
}
}