Skip to content

Commit 2660d60

Browse files
committed
better binpow
1 parent d43713c commit 2660d60

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

cp-algo/math/common.hpp

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include <functional>
44
#include <cstdint>
55
#include <cassert>
6+
#include <bit>
67
namespace cp_algo::math {
78
#ifdef CP_ALGO_MAXN
89
const int maxn = CP_ALGO_MAXN;
@@ -12,16 +13,17 @@ namespace cp_algo::math {
1213
const int magic = 64; // threshold for sizes to run the naive algo
1314

1415
auto bpow(auto const& x, auto n, auto const& one, auto op) {
15-
if(n == 0) {
16+
if (n == 0) {
1617
return one;
17-
} else {
18-
auto t = bpow(x, n / 2, one, op);
19-
t = op(t, t);
20-
if(n % 2) {
21-
t = op(t, x);
18+
}
19+
auto ans = x;
20+
for(int j = std::bit_width<uint64_t>(n) - 2; ~j; j--) {
21+
ans = op(ans, ans);
22+
if((n >> j) & 1) {
23+
ans = op(ans, x);
2224
}
23-
return t;
2425
}
26+
return ans;
2527
}
2628
auto bpow(auto x, auto n, auto ans) {
2729
return bpow(x, n, ans, std::multiplies{});

0 commit comments

Comments
 (0)