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

时间:2021-03-16 02:04:33

题目链接:

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,题目看错,一天都没什么思路,冷静一下。。

代码:

 #include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL; LL _n, p;
//快速加 -> x*n
LL pow_add(LL x,LL n) {
LL ret = , base = x;
while (n) {
if (n & ) {
ret = (ret + base) % p;
}
base = (base + base) % p;
n /= ;
}
return ret;
}
//快速幂 -> x^n
LL pow_mod(LL x,LL n) {
LL ret = , base = x;
while (n) {
if (n & ) {
ret = pow_add(ret, base);
}
base = pow_add(base, base);
n /= ;
}
return ret;
} int main() {
while (scanf("%lld%lld", &_n, &p) == && _n) {
LL ans = pow_mod(,_n);
ans = (ans + p - ) % p;
printf("%lld\n", ans);
}
return ;
}