我写了这两段代码(实现同一功能):
代码一:
public class Fibonacci {
public static void main ( String args[] ){
System.out.println( f5(100) );
}
public static int f5(int i){
if( i == 1 || i == 2 ){
return 1;
}else{
return f5( i - 1 ) + f5( i - 2 );
}
}
}
代码二:
public class Fibonacci2 {
public static void main( String args[] ) {
System.out.println( f(100) );
} public static long f( int index ) {
if( index <= 2 ){
return 1;
}
long sum = 0L;
long temp1 = 1 , temp2 = 1 ;
for( int i = 3 ; i <= index ; i++ ) {
sum = temp1 + temp2;
temp1 = temp2;
temp2 = sum;
}
return sum;
}
}
两段代码的运行速度一个很快一个很忙,为什么?最好能讲得详细点(包括起其中的原理)?谢谢!
代码一:
public class Fibonacci {
public static void main ( String args[] ){
System.out.println( f5(100) );
}
public static int f5(int i){
if( i == 1 || i == 2 ){
return 1;
}else{
return f5( i - 1 ) + f5( i - 2 );
}
}
}
代码二:
public class Fibonacci2 {
public static void main( String args[] ) {
System.out.println( f(100) );
} public static long f( int index ) {
if( index <= 2 ){
return 1;
}
long sum = 0L;
long temp1 = 1 , temp2 = 1 ;
for( int i = 3 ; i <= index ; i++ ) {
sum = temp1 + temp2;
temp1 = temp2;
temp2 = sum;
}
return sum;
}
}
两段代码的运行速度一个很快一个很忙,为什么?最好能讲得详细点(包括起其中的原理)?谢谢!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货