Google OR-Tools v9.12
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
constant_divisor.cc
Go to the documentation of this file.
1// Copyright 2010-2025 Google LLC
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
15
16#include <cstdint>
17#include <limits>
18
19#include "absl/log/check.h"
20#include "absl/numeric/int128.h"
21
22namespace util {
23namespace math {
24
25// Fast div/mod implementation based on
26// "Faster Remainder by Direct Computation: Applications to Compilers and
27// Software Libraries" Daniel Lemire, Owen Kaser, Nathan Kurz arXiv:1902.01961
29 : ConstantDivisorBase((absl::Uint128Max() / d) + 1, d) {
30 CHECK_GT(d, 1) << "ConstantDivisor<uint64_t> only supports denominators > 1.";
31}
32
33// If we hardcode shift_amount to 32, the 32-bit formula is:
34// magic_number = 2 ^ 64 / d
35// value / d = value * magic_number >> 64
36//
37// One caveat is that for d == 1, magic_number takes 65 bits overflowing a
38// uint64_t. So, we again disallow inputs with d == 1.
40 : ConstantDivisorBase((std::numeric_limits<MagicValueType>::max() / d) + 1,
41 d) {
42 CHECK_GT(d, 1) << "ConstantDivisor<uint32_t> only supports denominators > 1.";
43}
44
46 : ConstantDivisorBase((MagicValueType{1} << kShift) / d + 1, d) {
47 CHECK_GT(d, 0);
48}
49
51 : ConstantDivisorBase((MagicValueType{1} << kShift) / d + 1, d) {
52 CHECK_GT(d, 0);
53}
54
55} // namespace math
56} // namespace util
ConstantDivisor(value_type denominator)
STL namespace.
A collections of i/o utilities for the Graph classes in ./graph.h.