原文:https://bafanglvren.ink/archives/61/
717. 简单斐波那契
原题链接:https://www.acwing.com/problem/content/719/
题目
以下数列0 1 1 2 3 5 8 13 21 …被称为斐波纳契数列。
这个数列从第3项开始,每一项都等于前两项之和。
输入一个整数N,请你输出这个序列的前N项。
输入格式
一个整数N。
输出格式
在一行中输出斐波那契数列的前N项,数字之间用空格隔开。
数据范围
0<N<46
输入样例:
5
输出样例:
0 1 1 2 3
解
直接用一个int数组存放斐波那契数列,再输出即可。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
static int n;
static int a[] = new int[47];
public static void main(String[] args) throws Exception, IOException {
// TODO Auto-generated method stub
BufferedReader cin = new BufferedReader (new InputStreamReader(System.in));
n = Integer.valueOf(cin.readLine());
a[1] = 0;
a[2] = 1;
for(int i = 3;i<46;i++)
a[i] = a[i-1] + a[i-2];
for(int i = 1;i<=n;i++)
System.out.print(a[i] + " ");
}
}