Gibonacci number【斐波拉契】

链接:



G. Gibonacci number

2000ms
2000ms
65536KB
64-bit integer IO format:  %lld      Java class name:  Main
Font Size:   

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


思路:


设 G[1] = x
因为 G[0] = 1
所以 
G[2] = 1 + x
G[3] = 1 + 2x
G[4] = 2 + 3x
G[5] = 3 + 5x
..............

枚举几次就可以发现 

当 i >= 2 的时候 G[i] = f[i-2] + f[i-1]*x   【f[] 为斐波拉契数组。。。】

很容易就可以算出 G[20] 的最大值不会超过 long long 因为 X 最大才 一百万

所以先求出 G[1] = (G[i] - f[i-2]) / f[i-1];
如果能够整除,而且 G[1] >= 1 则可以按照上述公式输出结果即可
否则 X 非法输出 -1



坑:


RE:不能写 while(scanf("%d", &n) != EOF)
WA:1.注意数组边界
          2.注意算出的 t 【代码中的 x】 可能会 < 1 这是非法的,要直接输出 -1

说多了都是泪。。。
很容易的就推理出了公式,然后在这几个坑上和苦逼的 OJ 等待上错了 3 次,外加前面队友的大数错了 4 次,然后就苦逼了。。。。。
暑假最后一篇题解,马上就回家了,代码有点乱Orz


code:

#include<stdio.h>
#include<string.h>

const int maxn = 1000000;
long long f[40];
void inint()
{
	f[0] = f[1] = 1;
	for(int i = 2; i <= 30; i++) f[i] = f[i-1]+f[i-2];
}
int main()
{
	inint();
	int n;
	int i,j;
	long long g;
	scanf("%d", &n); 
	{
		while(n--)
		{
			scanf("%d%lld%d", &i,&g,&j);
			long long x;
			if(i > 1)
			{
				x = (g-f[i-2])/f[i-1];
			
				if(x*f[i-1] != (g-f[i-2]) || x < 1)
				{
				 	printf("-1\n"); continue;
				}
				if(j > 1) printf("%lld\n", f[j-2]+f[j-1]*x);
                else printf("%lld\n", x);
			}
			else if(i == 1)
			{
				x = g;
				if(x < 1)
				{
				 	printf("-1\n"); continue;
				}
				if(j == 1) printf("%lld\n", x);
				else printf("%lld\n", f[j-2]+f[j-1]*x);	
			}
		}
	}
	return 0;
} 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值