Skip to content

Commit d6e68a2

Browse files
madhur4127adamant-pwn
authored andcommitted
Add benchmark and non-C++20 solution
1 parent 2db5e1f commit d6e68a2

File tree

1 file changed

+8
-1
lines changed

1 file changed

+8
-1
lines changed

src/data_structures/sparse-table.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,13 +107,20 @@ lg[1] = 0;
107107
for (int i = 2; i <= MAXN; i++)
108108
lg[i] = lg[i/2] + 1;
109109
```
110-
With C++20 this can be optimized to:
110+
Alternatively, log can be computed on the fly in constant space and time:
111111
```c++
112+
// C++20
112113
#include <bit>
113114
int log2_floor(unsigned long i) {
114115
return std::bit_width(i) - 1;
115116
}
117+
118+
// pre C++20
119+
int log2_floor(unsigned long long i) {
120+
return 63 - (i ? __builtin_clzll(i) : 64);
121+
}
116122
```
123+
[This benchmark](https://quick-bench.com/q/SWARd6gSu9_RYZUN8PAGEEiimv0) shows that using `lg` array is slower because of cache misses.
117124
118125
Afterwards we need to precompute the Sparse Table structure. This time we define $f$ with $f(x, y) = \min(x, y)$.
119126

0 commit comments

Comments
 (0)