There are less than 60 years left till the 900-th birthday anniversary of a famous Italian mathematician Leonardo Fibonacci. Of course, such important anniversary needs much preparations.
Dima is sure that it'll be great to learn to solve the following problem by the Big Day: You're given a set A, consisting of numbers l, l + 1, l + 2, ..., r; let's consider all its k-element subsets; for each such subset let's find the largest common divisor of Fibonacci numbers with indexes, determined by the subset elements. Among all found common divisors, Dima is interested in the largest one.
Dima asked to remind you that Fibonacci numbers are elements of a numeric sequence, where F1 = 1, F2 = 1, Fn = Fn - 1 + Fn - 2 for n ≥ 3.
Dima has more than half a century ahead to solve the given task, but you only have two hours. Count the residue from dividing the sought largest common divisor by m.
Input
The first line contains four space-separated integers m, l, r and k (1 ≤ m ≤ 109; 1 ≤ l < r ≤ 1012; 2 ≤ k ≤ r - l + 1).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.
Output
Print a single integer — the residue from dividing the sought greatest common divisor by m.
Examples
10 1 8 2
3
10 1 8 3
1
题意:在l-r中取k个数,使他们作为下标对应的斐波那契数gcd值最大,输出这个最大值%m的值
题解:
首先是斐波那契数列的高妙性质
gcd(Fi[a],Fi[b])=Fi[gcd(a,b)]
所以问题变成了在l-r区间里找k个数使他们的gcd最大
这可以在sqrt(r)的范围内搞出来
再用矩阵快速幂求一波斐波那契第n个数的值就可以了
代码如下:
#include<map> #include<cmath> #include<cstdio> #include<vector> #include<cstring> #include<iostream> #include<algorithm> using namespace std; long long l,r,k,mod; struct matrix { long long m[3][3]; }; matrix mul(matrix a,matrix b) { matrix c; c.m[0][0]=(a.m[0][0]*b.m[0][0]+a.m[0][1]*b.m[1][0])%mod; c.m[0][1]=(a.m[0][0]*b.m[0][1]+a.m[0][1]*b.m[1][1])%mod; c.m[1][0]=(a.m[1][0]*b.m[0][0]+a.m[1][1]*b.m[1][0])%mod; c.m[1][1]=(a.m[1][0]*b.m[0][1]+a.m[1][1]*b.m[1][1])%mod; return c; } matrix kasumi(matrix a,long long b) { matrix ans; ans.m[0][0]=ans.m[1][1]=1; ans.m[1][0]=ans.m[0][1]=0; while(b) { if(b&1) { ans=mul(ans,a); } a=mul(a,a); b>>=1; } return ans; } int check(long long x) { long long uli=r/x*x; long long dli=l%x?(l/x+1)*x:l/x*x; return k<=(uli-dli)/x+1; } int main() { scanf("%lld%lld%lld%lld",&mod,&l,&r,&k); long long gg=0; for(long long i=1;i*i<=r;i++) { if(check(i)) gg=max(gg,i); if(check(r/i)) gg=max(gg,r/i); } matrix a; a.m[0][0]=a.m[1][0]=a.m[0][1]=1; a.m[1][1]=0; matrix ans=kasumi(a,gg); printf("%lld ",ans.m[0][1]%mod); }