您的位置:首页 > 其它

求Fibonacci数列:1,1,2,3,5,8,...第10个数的值

2011-08-23 19:56 507 查看
下面用两种方法实现:

第一种:使用递归调用实现

public class Fab{
public static void main(String[] args){
System.out.println(method(10));			//打印出方法method(10)的返回值
}

public static int method(int n){
if(index < 1){
System.out.println("invalid parameter!");
return -1;
}

if(n == 1 || n == 2){		      //如果传进来的参数等于1或2时直接返回1
return 1;
}else{						   			//否则返回前两个数之和
return method(n-1) + method(n-2);
}
}
}

第二种:用For循环来实现

public class Fab2{
public static void main(String[] args){
System.out.println(method(10));		//打印出方法method(10)的返回值
}

public static long method(long index){
if(index < 1){
System.out.println("invalid parameter!");
return -1;
}

if(index == 1 || index == 2){			//如果传进来的参数等于1或2时直接返回1
return 1;
}

long result1 = 1l;
long result2 = 1l;
long result = 0;

for(int i = 0; i < index-2; i++){		//因为等于1和2两个值直接返回1了,所以此处要给循环次数减去2
result = result1 + result2;
result1 = result2;
result2 = result;
}
return result;
}
}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: