求 1 1 2 3 5 8这种数列的第n个数 迭代法和递归来求

来源:互联网 发布:各种算法时间复杂度 编辑:程序博客网 时间:2024/05/16 05:38
public class testXunhuan {
public static void main(String[] args) {
System.out.println(f(40));
}
public static long f(int index){
if(index<0){
System.out.println("Error:输入错误,请输入大于0的值");
return -1;
}
long f1 = 1L;
long f2 = 1L;
long f=0;
for(int i=0;i<index-2;i++){
f=f1+f2;
f1=f2;//第2个数变为第1个数
f2=f;//和变为第2个数
}
return f;
}
}





public class testFoboni {

public static void main(String[] args) {
System.out.println(f(40));
}

public static int f(int i) {
if (i == 1 || i == 2) {
return 1;
} else {
return f(i - 1) + f(i - 2);
}
}

}
0 0