uva 10518 How Many Calls?

本文探讨了计算第n个斐波那契数时的函数调用次数,并考虑了取模运算来简化计算过程。通过预先计算循环节长度,实现了高效计算。

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

原题:
The fibonacci number is defined by the following recurrence:
• fib(0) = 0
• fib(1) = 1
• fib(n) = fib(n − 1) + fib(n − 2)
But we’re not interested in the fibonacci numbers here. We would like to know how many calls does
it take to evaluate the n-th fibonacci number if we follow the given recurrence. Since the numbers are
going to be quite large, we’d like to make the job a bit easy for you. We’d only need the last digit of
the number of calls, when this number is represented in base b.
Input
Input consists of several test cases. For each test you’d be given two integers n (0 ≤ n < 2 63 − 1), b
(0 < b ≤ 10000). Input is terminated by a test case where n = 0 and b = 0, you must not process this
test case.
Output
For each test case, print the test case number first. Then print n, b and the last digit (in base b) of the
number of calls. There would be a single space in between the two numbers of a line.
Note that the last digit has to be represented in decimal number system.
Sample Input
0 100
1 100
2 100
3 100
10 10
0 0
Sample Output
Case 1: 0 100 1
Case 2: 1 100 1
Case 3: 2 100 3
Case 4: 3 100 5
Case 5: 10 10 7

中文:
问你求第n个斐波那契数时,要调用多少次斐波那契函数(线性),结果取b的模。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll f[10001];
ll n,b;
ll solve(ll x)
{
    if(x==0||x==1)
        return 1;
    ll f1=1,f2=1;
    ll f3;
    for(int i=2;i<=x;i++)
    {
        f3=(f1+f2+1)%b;
        f1=f2;
        f2=f3;
    }
    return f3;
}
int main()
{
    ios::sync_with_stdio(false);
    f[1]=1;
    for(int i=2;i<=10000;i++)
    {
        ll tmp[100000]={1,1};
        for(int ind=2;;ind++)
        {
            tmp[ind]=(tmp[ind-1]+tmp[ind-2]+1)%i;
            if(tmp[ind]==1&&tmp[ind-1]==1)
            {
                f[i]=ind-1;
                break;
            }
        }
    }
    int t=1;
    while(cin>>n>>b,n+b)
    {
        if(b==1)
        {
            cout<<"Case "<<t++<<": "<<n<<" "<<b<<" "<<0<<endl;
            continue;
        }
        ll cnt=n%f[b];
//        cout<<cnt<<endl;
        ll ans=solve(cnt);
        cout<<"Case "<<t++<<": "<<n<<" "<<b<<" "<<ans<<endl;

    }
    return 0;
}

思路:

调用多少次函数的公式为
fib(i)=fib(i-1)+fib(i-2)+1

因为是取b的模,而b的值在10000以内,也就是会出现循环节
如果是取模的话
fib(i)=(fib(i-1)+fib(i-2)+1)%b
找到fib(i-1)=1且fib(i)=1时的i-1值,就是当前的循环节。提前打个表保存一下即可,也可以把这个循环节里面的所以数都算出来打表,更加方便。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值