ZZULIOJ 1259:Fibbonacci Number

文章讲述了如何使用C++编程解决斐波那契数列的问题。首先介绍了递归方法,但由于效率低可能导致超时,然后提出了使用数组存储计算结果以提高效率的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

Your objective for this question is to develop a program which will generate a fibbonacci number. The fibbonacci function is defined as such:

f(0) = 0

f(1) = 1

f(n) = f(n-1) + f(n-2)

Your program should be able to handle values of n in the range 0 to 50.

输入

Each test case consists of one integer n in a single line where 0≤n≤50. The input is terminated by -1.

输出

Print out the answer in a single line for each test case.

样例输入 Copy

3

4

5

-1

样例输出 Copy

2

3

5

来源/分类

浙江工业大学网络选拔赛


首先想到的是递归 但递归会时间超限,自己用vs跑 需要多几分钟才能出结果

int f(int n)
{
    if (n == 0)  //出口
        return 0;
    if (n == 1)
        return 1;
    else
        return f(n - 1) + f(n - 2);//关系
}
int main()
{
    int n;
    while (cin>>n)
    {
        if (n == -1)
            break;
        else
        cout << f(n) << endl;
    }
    return 0;
}

关于递归思想 我也是看b战老师讲解懂得

递归思想 点击可以学习一下

其次就是用数组 这个特别简单了

#include<iostream>
using namespace std;
int main()
{
    long long a[50],t;  //注意这里要 longlong类型 int会超出
    a[0] = 0; a[1] = 1;
    while (cin >> t)
    {
        if (t == -1)
            break;
        else {
            for (int i = 2; i <= t; i++)
                a[i] = a[i - 1] + a[i - 2];
            cout << a[t] << endl;
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KNeeg_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值