Best Solver HDU - 5451
The so-called best problem solver can easily solve this problem, with his/her childhood sweetheart.
It is known that
For a given integer
and a given prime number M (M≤46337), print [y]%M. ([y] means the integer part of y
)
Input
An integer T
, indicating there are T test cases.
Following are T lines, each containing two integers x and M
, as introduced above.
Output
The output contains exactly T lines.
Each line contains an integer representing [y]%M
.
Sample Input
7
0 46337
1 46337
3 46337
1 46337
21 46337
321 46337
4321 46337
Sample Output
Case #1: 97
Case #2: 969
Case #3: 16537
Case #4: 969
Case #5: 40453
Case #6: 10211
Case #7: 17947
题意:
求解
分析:
当我们看到带有根号的数的幂的时候,应该联想到斐波那契数列
因为斐波那契数列通项公式:
递推式:
因此我们应该想到需要构造类似于斐波那契数列通项公式这样的共轭式子来看能发现什么
我们构造
类比于斐波那契数列通项公式我们知道 必为整数,因为无理数在二项式展开后会相互消去
简单证明我们可以展开
当
为偶数的时候
变成整数,
当
为奇数的时候
和前面的恰好抵消
然后我们发现
而 是一个整数也就说明假设
(小数部分互补,使得整数部分+1)
而我们要求得的答案实际上是
因此我们得到答案
所以我们只要求出数列 来即可
继续类比斐波那契数列的递推公式
我们可以知道 的递推式必定也为
的形式
所以我们可以手动求出前几项带入求解系数
但我们也有更高级的计算方法,详细请看斐波那契数列通项公式推导及其类似构造共轭公式反求递推式
最终得到递推式
我们发现指数可能会非常大,但是题目却要求的取模。
所以我们再次对比斐波那契数列取模具有循环节的性质,这个数列取模也必含有循环节
所以对于每个给定的模数 我们每次可以打表找出循环节 ,然后求解系数
就得到了在一个循环节中的位置,也就是得到了数列 的第几项
然后输出 取模即可
code:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
const int maxn = 47000;
ll x;
int m,r[maxn],a[maxn];
void init(){
if(r[m] != -1)
return;
a[0] = 2 % m;
a[1] = 10 % m;
for(int i = 2;;i++){
a[i] = (10 * a[i-1] - a[i-2] + m) % m;
if(a[i-1] == a[0] && a[i] == a[1]){
r[m] = i-1;
break;
}
}
}
ll q_pow(ll b,ll mod){
ll ans = 1LL;
ll aa = 2LL;
while(b){
if(b & 1)
ans = ans * aa % mod;
b >>= 1;
aa = aa * aa % mod;
}
return ans;
}
void solve(){
int n,ans;
n = (int)q_pow(x,(ll)r[m]);
n = (n + 1) % r[m];
a[0] = 2 % m;//注意这里需要再求一边,因为如果r[m]之前已经算过了,将不初始化a数组,所以里面的值是上一个模数下的值
a[1] = 10 % m;
for(int i = 2; i <= n; i++){
a[i] = (10 * a[i-1] - a[i-2] + m) % m;
}
ans = (a[n] - 1 + m) % m;
printf("%d\n",ans);
}
int main(){
memset(r,-1,sizeof(r));
int T,cas = 0;
scanf("%d",&T);
while(T--){
scanf("%lld%d",&x,&m);
init();
printf("Case #%d: ",++cas);
solve();
}
return 0;
}