ZOJ Problem Set - 3702 Gibonacci number

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 forG(1) is a random integer t, (t>=1). Given thei-th Gibonacci number value G(i), and the numberj, 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 contains3 integers i, G(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 fort, output -1.

Sample Input
4
1 1 2
3 5 4
3 4 6
12 17801 19
Sample Output
2
8
-1
516847



题解:

公式推导:

斐波那契数列:                          G波那契:

f(0)=1                                          G(0)=1

f(1)=1                                          G(1)=t

f(2)=2                                          G(2)=1+t

f(3)=3                                          G(3)=1+2t

f(4)=5                                          G(4)=2+3t

f(5)=8                                          G(5)=3+5t

f(6)=13                                        G(6)=5+8t

f(7)=21                                        G(7)=8+13t


由上两个数列可推得:G(n)=f(n)-f(n-1)+f(n-1)*t

所以:

                     t={ G(n)-[f(n-1)-f(n-1)] } / f(n-1)

注意不能整除和小于等于0的情况(就是在这里WA里3次,人艰不拆啊!!!)

还有,不能用int,int会爆掉,举个极端例子就能发现输出的数是负的,如 1,1000000,20


代码:

#include<stdio.h>
using namespace std;
int main()
{
  int T;
  long long f[50],g[50];
  f[0]=1;f[1]=1;g[0]=1;
  for(int i=2;i<=20;i++)f[i]=f[i-1]+f[i-2];
  scanf("%d",&T);
  while(T--)
  {
    int i,j;
    long long z;
    scanf("%d%lld%d",&i,&z,&j);
    g[i]=z;
    long long t=g[i]-(f[i]-f[i-1]);
    if(t%f[i-1]||t<=0)
    {
      printf("-1\n");
      continue;
    }
    t/=f[i-1];
    g[1]=t;
    for(int k=2;k<=j;k++)g[k]=g[k-1]+g[k-2];
    printf("%lld\n",g[j]);
  }
  return 0;
}


方法二:看了12级一个师兄的代码是用二分暴力过的,数据才20个,1000000也不是很大。     

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值