1347: 又是斐波那契数列
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 562 Solved: 196
[Submit][Status][Web Board]
Description
在数学中斐波那契数列F是这样定义的:F(n)=F(n-1)+F(n-2),F(0)=1,F(1)=1。现在我有另外一个序列G,G(n)=G(n-1)+G(n-2),G(0)=1,G(1)=t(t>=1)。
你的任务对于给定的i,G(i)和j输出G(j)。
Input
多组测试数据,对于每组测试数据包含三个正整数i,G(i),j。1 <= i,j <=20, G(i)<100000。
Output
对于每组数据,如果t存在输出对应的G(j)的值,否则输出-1。
Sample Input
1 1 2
3 5 4
3 4 6
12 17801 19
Sample Output
2
8
-1
516847
HINT
Source
解题思路:
手写几个可以发现规律。G(3)=2t+1,G(4)=3t+2,G(5)=5t+3,可以发现每一项的系数是前一项的系数和常数之和,每一项的常数是前一项的系数,然后就可以算啦。
代码:
#include<bits/stdc++.h>
using namespace std;
int f(int n){
if(n==0)return 1;
else if(n==1)return 0;
else return f(n-1)+f(n-2);
}
int main()
{
int i,g,j,x,y,t;
while(scanf("%d%d%d",&i,&g,&j)!=EOF){
x=f(i+1);
y=g-f(i);
t=y/x;
if(y%x!=0 || t<1){
printf("-1\n");
continue;
}
x=f(j+1);y=x*t+f(j);
printf("%d\n",y);
}
return 0;
}