The GCD of Fibonacci Numbers

北城余情 提交于 2020-01-12 23:14:29

题目

The Fibonacci sequence is the sequence of numbers such that every element is equal to the sum of the two previous elements, except for the first two elements f0 and f1 which are respectively zero and one. The first few numbers in the Recaman’s Sequence is 0,1,1,2,3,5,8,… The i-th Fibonacci number is denoted fi.

The largest integer that divides both of two integers is called the greatest common divisor of these integers. The greatest common divisor of a and b is denoted by gcd(a,b).

Two positive integers m and n are given,you must compute the GCD(fm,fn).

Input

The first linecontains one integer T(T ≤ 100),the number of test cases.
For each test case,there are two positive integers m and n in one line. (1 ≤m,n ≤ 231 , GCD(m,n) ≤ 45)

Output

Foreach the case, your program will outputthe GCD(fm,fn).

Sample Input

Input

4
1 2
2 3
2 4
3 6

Output

1
1
1
2

思路

自己做的时候知道不可能暴力,看着求Fibonacci和Gcd差不多,找规律没找到~
                              f(x)=f(x1)+f(x2)f\left( x\right) =f\left( x-1\right) +f\left( x-2\right)
所以 当 m>nm>n时,有f(m)=f(n+1)f(mn)+f(mn1)f(n)f\left( m\right) =f\left( n+1\right) f\left( m-n\right) +f\left( m-n-1\right) f\left( n\right)  (自己推一下就可以出来撒)
所以有Gcd(f(m),f(n))=Gcd(f(n+1)f(mn)+f(mn1)f(n),f(n))Gcd\left( f\left( m\right) ,f\left( n\right) \right) =Gcd\left(f\left( n+1\right) f\left( m-n\right) +f\left( m-n-1\right) f\left( n\right),f\left( n\right) \right)
由求gcdgcd的更相减损术可知:Gcd(f(m),f(n))=Gcd(f(n+1)f(mn),f(n))Gcd\left( f\left( m\right) ,f\left( n\right) \right) =Gcd\left(f\left( n+1\right) f\left( m-n\right) ,f\left( n\right) \right)
                                                               进而可得:=Gcd(f(n+1),f(n))Gcd(f(mn),f(n))=Gcd\left(f\left( n+1\right) ,f\left( n\right) \right)*Gcd\left(f\left( m-n\right) ,f\left( n\right) \right)
                                                                              =Gcd(f(mn),f(n))=Gcd\left(f\left( m-n\right) ,f\left( n\right) \right)

所以此过程中mmnn互减,直到m%n==0m\%n==0时,对应的f(n)f(n)就是答案,所以求mmnn的最小公倍数,然后求其Fibonacci即可啦~
Gcd(f(m),f(n))=Gcd(f(mn),f(n))=......=f(Gcd(m,n))Gcd\left( f\left( m\right) ,f\left( n\right) \right) =Gcd\left(f\left( m-n\right) ,f\left( n\right) \right)=......=f\left( Gcd\left( m,n\right) \right)
Ps:f(n+1)f(n)Ps:f(n+1)和f(n)一定是互质的

代码如下

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<climits>
#include<cctype>
#include<queue>
#include<set>
using namespace std;
typedef unsigned long long ll;
const int INF=0x3f3f3f3f;
const int mx=2e5+10;

int t;
ll n,m,s[50];

ll fibo(ll a)
{
	if(s[a])
	return s[a];
	if(a==0)
	return 0;
	if(a==1)
	return 1;
	return s[a]=fibo(a-1)+fibo(a-2);
}

ll gcd(ll n,ll m)
{
	return n%m==0?m:gcd(m,n%m);
}

int main()
{
	fibo(50);
	s[0]=0,s[1]=1;
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%lld%lld",&n,&m);
		printf("%lld\n",s[gcd(n,m)]);
	}
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!