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)=1In 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也不是很大。