java用递归算法计算并输出Fibonacci数列的前20项

用java写用递归算法计算并输出Fibonacci数列的前20项

import java.util.HashMap;

public class Fib {
static HashMap<Integer, Integer> results = new HashMap<Integer, Integer>();

/**
 * F0 =0; <br>
 * F1=1 (n=1) <br>
 * F2=1 (n=2) <br>
 * Fn=Fn-1+Fn-2 (n>=3)
 */
public static int fib(int i) {
int result;
if (i == 0) {
result = 0;
} else if (i == 1) {
result = 1;
} else {
result = fib(i - 1) + fib(i - 2);
}
results.put(i, result);
return result;
}

public static void main(String[] args) {
int cnt = 20;
Fib.fib(cnt);
for (int i = 0; i < cnt; i++) {
System.out.printf("fib(%d) = %d\n", i, results.get(i));
}
}
}


简单实现.

递归是最差的算法.

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-02
public class Demo{
public static void main(String[] args) {
for(int i=1;i<=20;i++){
System.out.println(f(i));
}
}
public static int f(int n){
if(n == 1 || n ==2){
return 1;
}
return f(n-2)+f(n-1);
}
}
我自己写的,参考一下把本回答被网友采纳
第2个回答  2013-09-03
1 递归 自己调用自己
2 以上就是真谛
3 这个方法,被写烂了
4 自己琢磨琢磨,有好处

第3个回答  2013-09-03
class g
{
public int f(int r)
{
if(r==1 || r==2)
{
return 1;
}
else
{
return f(r-1)+f(r-2);
}
}
}
public class z
{
public static void main(String args[])
{
g value=new g();
System.out.println(value.f(20));
}
}
相似回答