1600: Big Mod (大数幂取模)

来源:互联网 发布:四级单词一笑而过软件 编辑:程序博客网 时间:2024/05/20 02:51
ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE3s8192K1756336Standard

Calculate

 

 

for large values of B, P, and M using an efficient algorithm. (That's right, this problem has a time dependency !!!.)

Input

Three integer values (in the order B, P, M) will be read one number per line. B and P are integers in the range 0 to 2147483647 inclusive. M is an integer in the range 1 to 46340 inclusive.

Output

The result of the computation. A single integer.

Sample Input

 

3181321717176532374859302938236123

Sample Output

 

13213195/*
*/
  1. #include <stdio.h>
  2. #include <memory>
  3. int main ()
  4. {
  5. int a,b,n;
  6. while (scanf("%d%d%d",&a,&b,&n)!=EOF)
  7. {
  8.   bool b2[35];
  9.   memset (b2,0,sizeof(b2));
  10.   int tmp=b,i,d=1;
  11.   for ( i=0; tmp>0 ; i++)
  12.   {
  13.    b2[i]=tmp%2;
  14.    tmp=tmp/2;
  15.   }
  16.   for (;i>=0;i--)
  17.    {
  18.    d=d*d%n;
  19.    int aa=a%n;
  20.    if ( b2[i]==1)
  21.     d=d*aa%n;
  22.    }
  23.    printf("%d/n",d);
  24. }
  25. return 0;
  26. }

方法二:超短代码

#include <cstdio>
int b, p, m, k;
int main()
{
 while(scanf("%d%d%d", &b, &p, &m)!=EOF)
    {
  for(k=1,b=b%m; p ; p/=2,b=b*b%m)
   if(p%2) k=k*b%m;
  printf("%d\n", k%m);
 }
 return 0;
}

 

方法三:递归 时间稍慢

#include <cstdio>
int m;
int bigmod(int a,int b)
{
    if(!b)return 1;
    int d=bigmod(a,b>>1)%m;
    return  b&1?(d*d%m*a)%m:(d*d)%m;
}
int main ()
{
    int a,b;
    while (scanf("%d%d%d",&a,&b,&m)!=EOF)
    {
        int ans=bigmod(a%m,b)%m;
        printf("%d\n",ans);
    }
    return 0;
}

快速幂取模 最短代码 for(k=1,a=a%m; b ; b>>=1,a=a*a%m) if(b&1) k=k*a%m; 求a^b(mod m) k%m是答案。