ZOJ 3702 Gibonacci number(数学推导题)

53 篇文章 0 订阅
32 篇文章 0 订阅

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3702
Gibonacci number


Time Limit: 2 Seconds       Memory Limit: 65536 KB

In mathematical terms, the normal sequence F(n) of Fibonacci numbers is defined by the recurrence relation

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

with seed values

F(0)=1, F(1)=1

In this Gibonacci numbers problem, the sequence G(n) is defined similar

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

with the seed value for G(0) is 1 for any case, and the seed value for G(1) is a random integer t(t>=1). Given the i-th Gibonacci number value G(i), and the number j, your task is to output the value for G(j)

Input

There are multiple test cases. The first line of input is an integer T < 10000 indicating the number of test cases. Each test case contains 3 integers iG(i) and j. 1 <= i,j <=20, G(i)<1000000

Output

For each test case, output the value for G(j). If there is no suitable value for t, output -1.

Sample Input
4
1 1 2
3 5 4
3 4 6
12 17801 19
Sample Output
2
8
-1
516847
 
题意:给出一个数列的第0项和第i项的值以及i,求第j项的值是多少。其中G(0)=1,G[i] = G[i-1] + G[i-2]。
分析:经过推导可以发现,G[i] = fib[i-2] * G[0] + fib[i-1] * G[1],又因为G[0]=1,所以G[i] = fib[i-2] + fib[i-1] * G[1]其中fib[i]表示斐波那契数列的第i项。所以我们只需要求出G[1],就可以求出G[j]了。注意有些要特判。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
using namespace std;

typedef long long LL;
const int N = 1e5 + 10;
long long fib[25];

void Init() {  // 预处理出斐波那契数列数列的前21项
    fib[0] = fib[1] = 1;
    for(int i = 2; i <= 20; i++)
        fib[i] = fib[i-1] + fib[i-2];
}

int main()
{
    Init();
    int T;
    LL a, n, k;
    scanf("%d", &T);
    while(T--) {
        scanf("%lld%lld%lld", &a, &n, &k);
        if(a == 1) {  // 若G[1]已给出
            if(k == 1) printf("%lld\n", n);
            else {
                printf("%lld\n", fib[k-2] + fib[k-1] * n);
            }
        }
        else {
            // G[i] = fib[i-2] + fib[i-1] * G[1]
            LL p = n - fib[a-2];
            if(p % fib[a-1] != 0 || p <= 0) {
                printf("-1\n");
                continue;
            }
            else {
                LL q = p / fib[a-1];
                if(k == 1) printf("%lld\n", q);
                else printf("%lld\n", fib[k-2] + fib[k-1] * q);
            }
        }
    }
    return 0;
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值