1600: Big Mod (大數冪模數)

來源:互聯網
上載者:User
Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 1756 336 Standard

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是答案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.