分治之快速幂模版

 1 /*
 2 快速幂模版
 3 求x^t%mod
 4 时间复杂度:O(logn)
 5 注:递归可能爆栈
 6 原理:x^t = (x^(t/2))^2 + x^(n%2);
 7 */
 8 #include <iostream>
 9 using namespace std;
10 long long quick_pow(long long x, long long t, long long mod)
11 {
12     if(t == 0) return 1;
13     long long temp = quick_pow(x, t / 2, mod);
14     temp = temp * temp % mod;
15     if(t % 2 == 1) temp = temp * x % mod;
16     return temp;
17 }
18 long long quick_pow2(long long x, long long t, long long mod)
19 {
20     long long ret = 1;
21     while(t)
22     {
23         if(t % 2)ret = ret * x % mod;
24         x = x * x % mod;
25         t >>= 1;
26     }
27     return ret;
28 }
29 int main()
30 {
31     long long x, t, mod;
32     cin >> x >> t >> mod;
33     cout << quick_pow(x, t, mod) << endl;
34     cout << quick_pow2(x, t, mod) << endl;
35     return 0;
36 }

 

posted @ 2017-08-14 11:53  Posase  阅读(115)  评论(0编辑  收藏  举报