public class Demo {
public static void main(String[] args) {
int n = 20;
int sum = 0;
for (int i = 1; i <= n; i++) {
System.out.print(fibo(i) + "\t");
sum +=fibo(i);
}
System.out.println("\n菲波那契数列的前20项和为:"+sum);
}
private static int fibo(int n) {
if (n == 1)
return 1;
if (n == 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
}
数组法:
public class Demo {
public static void main(String[] args) {
int []array=new int[20];
array[0]=1;
array[1]=1;
int sum = 0;
for (int i=2;i array[i]=array[i-1]+array[i-2];
}
//遍历数组并累计
for (int i=0;i sum +=array[i];
}
//输出和
System.out.println("\n菲波那契数列的前20项和为:"+sum);
}
}