Skip to content

Add portable formulas for fenwick calculations #1298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/data_structures/fenwick.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,18 @@ $$h(i) = i + (i ~\&~ (-i)).$$

As you can see, the main benefit of this approach is that the binary operations complement each other very nicely.

**Note**: for improved portability, the extraction of the last set bit can alternatively be computed as $i - (i ~\&~ (i-1))$. Accordingly:

$$g(i) = i ~\&~ (i-1)$$

and

$$h(i) = 2i - (i ~\&~ (i-1)).$$

This also allows the code for $g(i)$ to be succinctly written as `i &= i - 1`.

An example of this lack of portability is any version of C++ prior to C++20. Before [C++20](https://en.cppreference.com/w/cpp/20), it was not guaranteed for signed integers to be implemented as [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement), so the use of negative numbers ($-i$) alongside bitwise-and ($~\&~$) could ([theoretically](https://en.cppreference.com/w/cpp/language/types#Range_of_values)) lead to unexpected results.

The following implementation can be used like the other implementations, however it uses one-based indexing internally.

```{.cpp file=fenwick_sum_onebased}
Expand Down Expand Up @@ -335,6 +347,21 @@ struct FenwickTreeOneBasedIndexing {
}
};
```
An equivalent implementation which utilizes the more portable formulas would have the following changes:

```cpp
int sum(int idx) {
int ret = 0;
for (++idx; idx > 0; idx &= idx - 1)
ret += bit[idx];
return ret;
}

void add(int idx, int delta) {
for (++idx; idx < n; idx += idx - (idx & (idx - 1))
bit[idx] += delta;
}
```

## Range operations

Expand Down
Loading