NYOJ 102 次方求模

超时的代码

 1  
 2 #include<stdio.h>
 3 
 4 int main()
 5 {
 6     int T;
 7     scanf("%d",&T);
 8     while(T--)
 9     {
10       int  a,b,c,i,s=1;
11       scanf("%d %d %d",&a, &b ,&c);
12       for(i=0;i<b;i++)
13       {
14         s*=a;
15         s%=c;
16       }
17       printf("%d\n",s);
18     }
19     return 0;
20 }
21         

AC 的代码

 1  
 2 #include<stdio.h>
 3 
 4 int  jg( int a ,int b, int c)
 5 {
 6   long long int t;
 7   if(b==0) return 1;
 8   if(b==1) return a%c;
 9   t=jg(a,b/2,c)%c;
10   t=(t*t)%c;
11   if(b&1)
12   t=t*a%c;
13   return t;
14    
15    
16 }
17 int main()
18 {
19     int T;
20     scanf("%d",&T);
21     while(T--)
22     {
23       int  a,b,c,i,s=1;
24       scanf("%d %d %d",&a, &b ,&c);
25      printf("%d\n" ,jg(a,b,c));
26      
27     }
28     return 0;
29 }
30         

 

posted @ 2013-08-22 16:37  hpu张亚飞  阅读(216)  评论(0编辑  收藏  举报