HDU 5187 zhx's contest 快速幂,快速加

题目链接:

hdu: http://acm.hdu.edu.cn/showproblem.php?pid=5187

bc(中文): http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=571&pid=1002

 

题解:

求(2^n-2)%p,题目看错,一天都没什么思路,冷静一下。。

代码:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 typedef long long LL;
 6 
 7 LL _n, p;
 8 //快速加 -> x*n
 9 LL pow_add(LL x,LL n) {
10     LL ret = 0, base = x;
11     while (n) {
12         if (n & 1) {
13             ret = (ret + base) % p;
14         }
15         base = (base + base) % p;
16         n /= 2;
17     }
18     return ret;
19 }
20 //快速幂 -> x^n
21 LL pow_mod(LL x,LL n) {
22     LL ret = 1, base = x;
23     while (n) {
24         if (n & 1) {
25             ret = pow_add(ret, base);
26         }
27         base = pow_add(base, base);
28         n /= 2;
29     }
30     return ret;
31 }
32 
33 int main() {
34     while (scanf("%lld%lld", &_n, &p) == 2 && _n) {
35         LL ans = pow_mod(2,_n);
36         ans = (ans + p - 2) % p;
37         printf("%lld\n", ans);
38     }
39     return 0;
40 }

 

posted @ 2016-04-24 21:03  fenicnn  阅读(245)  评论(0编辑  收藏  举报