Hdu4704 Sum(又见费马小定理)

来源:互联网 发布:高清网络硬盘播放器 编辑:程序博客网 时间:2024/06/05 11:47

Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1130    Accepted Submission(s): 505


Problem Description
 

Sample Input
2
 

Sample Output
2
Hint
1. For N = 2, S(1) = S(2) = 1.2. The input file consists of multiple test cases.


题意:将N拆分成1-n个数,问有多少种组成方法。比如Sn=s1+s2+s3+..sn,S(n+1)=s1+s2+s3+...sn+s(n+1);S(n+1)=2Sn.所以Sn=2^(n-1)。但是这个n非常大。本来想用二进制快速幂这个n,无果。小费马定理的公式都知道:a^(p-1) %p=1  也就是说这个式子可以用1来代替。比如A是a的逆元A*a%p=1.我们可以把这个式子变成a*a*(p-2)%p=1;这个公式化简就是上面的小费马定理,我们可以把A看做是a^(p-2)%p=1、所以a的逆元就是这个东西。好了,言归正传。这个题目我们可以把n分解。变成多少个(p-1)+k。也就是    (t*(p-1)+k) %p。根据同余定理,2^t(p-1)%p正好等于1,乘上一个数没有影响,所以只剩下2^k % p。这个k就是小于1e9+7的数,再运用快速幂求(2,k)即可。

对于任意自然数,当要求a^p%m时,就可以利用费马小定理化简,只需求(a^(p%(m-1)))%m;(p是素数)

#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <iostream>#include <cmath>#include <queue>#include <map>#include <stack>#include <list>#include <vector>using namespace std;#define LL long longconst LL M=1e9+7;char s[100010];LL xiaofeima(LL m){int l=strlen(s);LL ans=0;for (int i=0;i<l;i++)ans=(ans*10+s[i]-'0') %m;return ans;}LL ksm(LL a,LL b){LL ans=1;while (b){if (b % 2==1)ans=ans*a%M;a=a*a%M;b>>=1;}return ans;}int main(){while (gets(s)){LL k=xiaofeima(M-1);//cout<<k<<endl;cout<<ksm(2,k-1)<<endl;}return 0;}


0 0
原创粉丝点击