We use boost::multiprecision::cpp_rational
to represent fractions.
At some point, I have to determine if a sum of a potentially huge number of fractions reaches 1 or not. I don’t care about the exact value of the sum; not even if it’s exactly 1 or above. The individual fractions are all between 0 and 1 (both exclusive).
Is there some clever math trick that I’m not aware of that spares me from actually having to calculate the sum?
There are some domain-specific considerations:
- Getting a lot of fractions with the same denominators is a common case and not a rare happenstance.
- The case where the sum is exactly 1 is a common case.
- The sum exceeding 1 by a large amount (exceeding 2) is probably so rare it essentially never happens.
My optimization attempts so far:
As a first step, I already calculate partial sums in a std::map
that “sorts” the fractions by denominator and adds same-denominator fractions first.
The partial sums are then sorted by size, largest first.
But after that, I just add them and after each addition, check if the result is already greater or equal than 1 and quit early if they are (that’s because the fractions are all positive).