hdu1420 Prepared for New Acmer 简单数学

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1420

简单数学题

第一次wa在可能和会出现取模后值为负数的情况。

只要会一个数论上的简单公式(a*b)%c=((a%c)*(b%c))%c 其中*可以为加,减,乘,除。计算时保留中间结果可以避免重复,极大的提升时间效率。

我的代码运行时间为0ms

代码如下:

 1 #include<iostream>
 2 #include<cmath>
 3 #include<cstdlib>
 4 #include<cstdio>
 5 using namespace std;
 6 long long int a,b,c;
 7 int Mulite(long  long int a,long long int b)
 8 {
 9         if(b==1) return a%c;
10         if(b%2==0){
11                 long long int temp=((Mulite(a,b/2))%c+c)%c;
12                 return ((temp*temp)%c+c)%c;
13                   }
14         else 
15              if(b%2) {
16                      long long int temp2=(Mulite(a,b/2)%c+c)%c;
17                      long long int temp3=((temp2*(a%c))%c+c)%c;
18                      return((temp2*temp3)%c+c)%c;
19                      }
20 }
21 int main()
22 {
23         int n;
24         scanf("%d",&n);
25         while(n--)
26         {
27                 scanf("%lld%lld%lld",&a,&b,&c);
28                cout<<Mulite(a,b);
29                cout<<endl;
30         }
31         return 0;
32        
33 }
View Code

 

posted on 2013-08-07 12:48  GyyZyp  阅读(191)  评论(0编辑  收藏  举报

导航