Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 913 Accepted Submission(s): 385
/*超时。。。。呜呜 #include <stdio.h> int main() { __int64 n,m,i,j,a; while(scanf("%I64d",&n),n) { m=n-1; a=2; for(i=1;i<m;) { if(i*2<=m) { a=a*a%n; i=i*2; } else { a=a*2%n; i++; } } printf("%I64d\n",(a+1)%n); } return 0; }*/
优化后的代码。。。
#include<stdio.h> int main() { __int64 n,m,i,k,a,bit[100]; while(scanf("%I64d",&n),n) { a=1; k=0; m=n-1; while(m) { bit[k++]=m%2;//判断奇偶 m=m>>1;//m/=2; } for(i=k-1;i>=0;i--) { a=a*a%n; if(bit[i]==1) a=a*2%n; } printf("%d\n",(a+1)%n); } return 0; }
原文:http://www.cnblogs.com/yuyixingkong/p/3539715.html