我有一个递归Fibonacci序列的跟随代码
if (term < 2){
System.out.print("1 ");
return 1;
}
int results = fibonacci(term - 1) + fibonacci(term - 2);
System.out.print(results + " ");
return results;
我得到的输出是
您希望Fibonacci序列达到以下哪个术语:4
1 1 2 1 3 1 1 2 5第4是5
如何制作它以便打印
1 1 2 3第4个是5
答案 0 :(得分:1)
使用尾递归。
public static void main(String[] args) {
System.out.print("The 10th is: " + fibonnaci(10));
}
public static int fibonnaci(int number) {
return fibonnaciHelper(number, 1, 1);
}
public static int fibonnaciHelper(int term, int lower, int higher) {
if (term < 2){
return higher;
}
System.out.print(higher + " ");
int results = fibonnaciHelper(term - 1, higher, higher + lower);
return results;
}
答案 1 :(得分:0)
迭代的斐波那契序列 - 让它躺在某处
public static int fib(int n) {
int prev1=0, prev2=1;
for(int i=0; i<n; i++) {
int savePrev1 = prev1;
prev1 = prev2;
prev2 = savePrev1 + prev2;
}
return prev1;
}
答案 2 :(得分:0)
您可以尝试以下内容:
public void fib(int n){
if(n==0)
System.out.println(1);
else System.out.println(fib(1,n,0,1);
}
private int fib(int iteration, int limit, int n0, int n1){
if(iteration==limit)
return(n0+n1);
fib(++iteration,limit,n1,(n0+n1));
}