蓝桥杯:递推717:简单斐波那契

以下数列 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值