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 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 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 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
解析:此题是斐波那契数列的变形,知道斐波那契数列的第一项为1,然后给出第i项的值,求第j项的结果。通过数学递推公式可得,G(i)由n个G(0)加m个G(1)的和。而n和m分别是两个斐波那契数列中的i-2项。
首先用(G(i)-n*G(0))%m==0判断是否存在一个整数G(1)。如果存在这样一个数,还要注意G(1)是否大于等于1;
#include"stdio.h"
long long g[100];
void cal(long long x)
{
int i;
g[1]=x;
for(i=2;i<21;i++)
g[i]=g[i-1]+g[i-2];
}
int main()
{
int n,i,j,a,b;
long long k;
int aa[22],bb[22];
scanf("%d",&n);
aa[0]=1;aa[1]=2;
g[0]=1;
for(i=2;i<21;i++)
aa[i]=aa[i-1]+aa[i-2];
bb[0]=1;bb[1]=1;
for(i=2;i<21;i++)
bb[i]=bb[i-1]+bb[i-2];
while(n--)
{
scanf("%d %lld %d",&i,&k,&j);
if(i==1)
{
cal(k);
printf("%lld\n",g[j]);
}
else
if(i>1)
{
if((k-bb[i-2])%aa[i-2]==0)
{
if((k-bb[i-2])/aa[i-2]<1)
{
printf("-1\n");
}
else{
cal((k-bb[i-2])/aa[i-2]);
printf("%lld\n",g[j]);
}
}
else
printf("-1\n");
}
}
return 0;
}