以下数列 0 1 1 2 3 5 8 13 21 ... 被称为斐波纳契数列。
这个数列从第 3 项开始,每一项都等于前两项之和。
输入一个整数 N,请你输出这个序列的前 N 项。
输入格式
一个整数 N。
输出格式
在一行中输出斐波那契数列的前 N 项,数字之间用空格隔开。
数据范围
0<N<46
输入样例:
5
输出样例:
0 1 1 2 3
第一种:数存数组里,直接由前两位求得。注意1,2是特殊情况。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
const int N=50;
int num[N];
int main(){
cin>>n;
num[1]=0;
num[2]=1;
if(n==1){cout<<0;}
else if(n==2){cout<<0<<" "<<1;}
else{
cout<<0<<" "<<1<<" ";
for(int i=3;i<=n;i++){
num[i]=num[i-1]+num[i-2];
cout << num[i] << " ";
}
}
return 0;
}
第二种:为了节省空间,不必开数组,只需要a,b用来记录前面两个数:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
int a,b;
int num;
int main(){
cin>>n;
a=0;
b=1;
if(n==1){cout<<a;}
else if(n==2){cout<<a<<" "<<b;}
else{
cout<<0<<" "<<1<<" ";
for(int i=3;i<=n;i++){
num=a+b;
cout << num<< " ";
a=b;
b=num;
}
}
return 0;
}