競技プログラミング用の C++ ライブラリ
#include "src/math/quotients.hpp"$\lfloor n / i \rfloor$、または $\lfloor (ax+b)/m \rfloor$ が同じ値になる最大の半開区間を列挙します。$\lfloor n / i \rfloor$ がとる値は $O(\sqrt{n})$ 種類しかないので (区間の個数は $2\sqrt{n}$ 以下)、$\sum_{i=1}^{n} f(\lfloor n/i \rfloor)$ のような和を、区間ごとにまとめて $O(\sqrt{n})$ で計算できます。
例えば $n = 10$ では、次の 5 つの区間に分かれます。
商 q
|
10 | 5 | 3 | 2 | 1 |
|---|---|---|---|---|---|
区間 [l, r)
|
[1, 2) | [2, 3) | [3, 4) | [4, 6) | [6, 11) |
// sum_{i=1}^{n} floor(n / i) (= 約数の個数の和 d(1) + ... + d(n))
long long sum = 0;
for_each_quotient(n, [&](long long q, long long l, long long r) { sum += q * (r - l); });
for (auto [q, l, r] : enumerate_quotients(10)) {
// (10, 1, 2), (5, 2, 3), (3, 3, 4), (2, 4, 6), (1, 6, 11) の順
}
// floor(x / 3) が同じになる区間 (0 <= x < 10)
for (auto [q, l, r] : enumerate_quotients_linear(10, 3, 1, 0)) {
// (0, 0, 3), (1, 3, 6), (2, 6, 9), (3, 9, 10) の順
}
// sum_{x=0}^{n-1} floor((a*x+b)/m)
long long linear_sum = 0;
for_each_quotient_linear(n, m, a, b, [&](long long q, long long l, long long r) { linear_sum += q * (r - l); });
_linear 版の引数順は floor_sum(n, m, a, b) と同じです。対象は 0 <= x < n で、a、b は負でもよく、床関数は負の無限大方向への切り捨てです。n >= 0、m >= 1、各商が long long に収まることが前提です。中間計算には __int128 を使います。
どちらの版も添字の昇順に列挙し、n = 0 では区間を返しません。_linear 版の商は a > 0 なら昇順、a < 0 なら降順です。a = 0 で n > 0 なら全域を 1 区間として返します。以下では _linear 版の出力区間数を $K$ とします。
返される range は区間を走査時に生成します。size()・添字アクセス・逆順走査はありません。イテレータは値を返す input iterator で、それぞれ独立した状態を持ち、同じ range を繰り返し走査できます。途中で break すると残りの区間は生成しません。
保存や逆順走査が必要な場合は、明示的に vector に変換します。
auto ranges = enumerate_quotients(n);
std::vector<QuotientRange> saved(ranges.begin(), ranges.end());
_linear 版の a = 1 は、最初の商と余りを求めた後、境界と商を加算だけで進めます。
| 関数 | 説明 | 計算量 |
|---|---|---|
for_each_quotient(n, f) |
区間ごとに f(q, l, r) を呼ぶ。$l \le i < r$ なら $\lfloor n/i \rfloor = q$ |
$O(\sqrt{n})$ |
enumerate_quotients(n) |
区間を QuotientRange (メンバ q、l、r) として遅延列挙する range を返す |
構築 $O(1)$、全走査 $O(\sqrt{n})$ |
for_each_quotient_linear(n, m, a, b, f) |
$\lfloor (ax+b)/m \rfloor$ が一定の区間ごとに f(q, l, r) を呼ぶ |
$O(K)$ |
enumerate_quotients_linear(n, m, a, b) |
上の区間を遅延列挙する range を返す | 構築 $O(1)$、全走査 $O(K)$ |
[l, r) は右端を含まない半開区間です。区間の長さは r - l です。0 <= n < std::numeric_limits<long long>::max() です。商は降順に並びます。商の昇順が欲しいときは vector に格納して逆にたどります。_linear 版は $K \le n$ ですが、平方根程度になる保証はありません。両方の列挙 API の追加領域は $O(1)$ です (コールバックの時間・領域は除く)。a = 1, b = 0 のとき区間数は $\lceil n/m\rceil$ です。異なる正整数の m を $D$ 個処理する総区間数は $O(D+n\log(D+1))$ になります。#pragma once
/**
* @file quotients.hpp
* @brief 商の列挙 (floor(n / i)・floor((a x + b) / m) が一定の区間)
*/
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#include "../base/functions.hpp"
/**
* @brief 商 q と、それをとる添字の区間 [l, r)
*/
struct QuotientRange {
long long q; //!< 商
long long l; //!< 区間の左端 (含む)
long long r; //!< 区間の右端 (含まない)
};
namespace internal_quotients {
struct Quotients {
long long n = 0;
QuotientRange current{0, 1, 1};
bool done = true;
void advance() {
const long long l = current.r;
done = l > n;
if (!done) {
const long long q = n / l;
current = {q, l, n / q + 1};
}
}
};
struct QuotientsLinear {
long long n = 0, m = 1, a = 0, b = 0;
QuotientRange current{0, 0, 0};
bool done = true;
void advance() {
const long long l = current.r;
done = l == n;
if (done) return;
if (a == 1) {
long long q, length;
if (l == 0) {
auto [initial_q, rem] = divmod(static_cast<__int128_t>(b), static_cast<__int128_t>(m));
q = static_cast<long long>(initial_q);
length = m - static_cast<long long>(rem);
} else {
assert(current.q < std::numeric_limits<long long>::max());
q = current.q + 1;
length = m;
}
current = {q, l, l + std::min(length, n - l)};
return;
}
advance_general(l);
}
// 加算だけで進む a == 1 の更新をインライン化しやすいよう、汎用計算を分ける。
void advance_general(long long l) {
const __int128_t slope = a;
auto [q, rem] = divmod(slope * l + b, static_cast<__int128_t>(m));
assert(std::numeric_limits<long long>::min() <= q && q <= std::numeric_limits<long long>::max());
__int128_t length = n - l;
// 正の傾きでは次の商に届くまで、負の傾きでは余りが負になるまで進む
if (a > 0) chmin(length, ceildiv(m - rem, slope));
if (a < 0) chmin(length, rem / (-slope) + 1);
current = {static_cast<long long>(q), l, l + static_cast<long long>(length)};
}
};
// イテレータが状態を所有するため、range の寿命や別の走査に依存しない。
template <class State>
class Enumeration {
State initial;
public:
explicit Enumeration(State initial) : initial(initial) {}
class iterator {
State state;
public:
using value_type = QuotientRange;
using difference_type = std::ptrdiff_t;
using reference = value_type;
using pointer = void;
using iterator_category = std::input_iterator_tag;
iterator() = default;
explicit iterator(State state) : state(state) { this->state.advance(); }
value_type operator*() const { return state.current; }
iterator& operator++() {
state.advance();
return *this;
}
iterator operator++(int) {
auto previous = *this;
++*this;
return previous;
}
bool operator==(const iterator& other) const {
if (state.done || other.state.done) return state.done == other.state.done;
return state.current.l == other.state.current.l;
}
bool operator!=(const iterator& other) const { return !(*this == other); }
};
iterator begin() const { return iterator(initial); }
iterator end() const { return iterator(); }
};
} // namespace internal_quotients
/**
* @brief floor(n / i) が一定の区間を添字の昇順 (商の降順) に遅延列挙する。全体 O(sqrt(n))、追加領域 O(1)
* @pre 0 <= n < std::numeric_limits<long long>::max()
*/
inline auto enumerate_quotients(long long n) {
assert(0 <= n && n < std::numeric_limits<long long>::max());
return internal_quotients::Enumeration(internal_quotients::Quotients{n});
}
/**
* @brief x = 0, ..., n - 1 を floor((a x + b) / m) の値で区間に分け、x の昇順に遅延列挙する。全体 O(区間数)、追加領域 O(1)
* @pre n >= 0、m >= 1、各商が long long に収まること。a, b は負でもよい
*/
inline auto enumerate_quotients_linear(long long n, long long m, long long a, long long b) {
assert(n >= 0 && m >= 1);
return internal_quotients::Enumeration(internal_quotients::QuotientsLinear{n, m, a, b});
}
/**
* @brief floor(n / i) が一定の区間ごとに f(q, l, r) を呼ぶ O(sqrt(n))
*/
template <typename F>
void for_each_quotient(long long n, F f) {
for (auto [q, l, r] : enumerate_quotients(n)) f(q, l, r);
}
/**
* @brief floor((a x + b) / m) が一定の区間ごとに f(q, l, r) を呼ぶ O(区間数)
*/
template <typename F>
void for_each_quotient_linear(long long n, long long m, long long a, long long b, F f) {
for (auto [q, l, r] : enumerate_quotients_linear(n, m, a, b)) f(q, l, r);
}#line 2 "src/math/quotients.hpp"
/**
* @file quotients.hpp
* @brief 商の列挙 (floor(n / i)・floor((a x + b) / m) が一定の区間)
*/
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#line 2 "src/base/functions.hpp"
/**
* @file functions.hpp
* @brief 汎用関数 (chmin, chmax など)
*/
#line 9 "src/base/functions.hpp"
#include <cmath>
#line 12 "src/base/functions.hpp"
#include <numeric>
#if __cplusplus >= 202002L
#include <ranges>
#endif
#include <type_traits>
#include <utility>
template <typename T1, typename T2>
inline constexpr bool chmin(T1& a, T2 b) {
if (a > b) {
a = b;
return true;
}
return false;
}
template <typename T1, typename T2>
inline constexpr bool chmax(T1& a, T2 b) {
if (a < b) {
a = b;
return true;
}
return false;
}
inline constexpr long long max(const long long& t1, const long long& t2) {
return std::max<long long>(t1, t2);
}
inline constexpr long long min(const long long& t1, const long long& t2) {
return std::min<long long>(t1, t2);
}
using std::abs;
using std::gcd;
using std::lcm;
using std::size;
#if __cplusplus >= 202002L
using std::midpoint;
#else
// C++20 の std::midpoint と同じ (整数は a の側に丸め、あふれない)
template <typename T>
inline constexpr std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, T> midpoint(T a, T b) noexcept {
using U = std::make_unsigned_t<T>;
if (a <= b) return static_cast<T>(a + static_cast<T>(static_cast<U>(static_cast<U>(b) - static_cast<U>(a)) >> 1));
return static_cast<T>(a - static_cast<T>(static_cast<U>(static_cast<U>(a) - static_cast<U>(b)) >> 1));
}
template <typename T>
inline constexpr std::enable_if_t<std::is_floating_point_v<T>, T> midpoint(T a, T b) noexcept {
constexpr T lo = std::numeric_limits<T>::min() * 2;
constexpr T hi = std::numeric_limits<T>::max() / 2;
const T abs_a = a < 0 ? -a : a, abs_b = b < 0 ? -b : b;
if (abs_a <= hi && abs_b <= hi) return (a + b) / 2;
if (abs_a < lo) return a + b / 2;
if (abs_b < lo) return a / 2 + b;
return a / 2 + b / 2;
}
template <typename T>
inline constexpr std::enable_if_t<std::is_object_v<T>, T*> midpoint(T* a, T* b) noexcept {
return a + (b - a) / 2;
}
#endif
/**
* 要素数を long long で返す (std::ssize の long long 版)
* size() を持つ型なら、begin() と end() を持たない自作の型にも使える
*/
#if __cplusplus >= 202002L
template <typename R>
requires requires(R& r) { std::ranges::size(r); }
inline constexpr long long len(R&& r) {
return static_cast<long long>(std::ranges::size(r));
}
#else
template <typename C>
inline constexpr auto len(const C& c) -> decltype(static_cast<long long>(std::size(c))) {
return static_cast<long long>(std::size(c));
}
#endif
template <typename T>
constexpr T extgcd(const T& a, const T& b, T& x, T& y) {
T d = a;
if (b != 0) {
d = extgcd(b, a % b, y, x);
y -= (a / b) * x;
} else {
x = 1;
y = 0;
}
return d;
}
/**
* floor(a / b) (b != 0、負の数も可)
*/
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> floordiv(T1 a, T2 b) {
return a / b - (a % b != 0 && (a < 0) != (b < 0));
}
/**
* ceil(a / b) (b != 0、負の数も可)
*/
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> ceildiv(T1 a, T2 b) {
return a / b + (a % b != 0 && (a < 0) == (b < 0));
}
/**
* {floor(a / b), a - b * floor(a / b)} (b != 0、負の数も可)
* 余りは 0 または b と同じ符号になる
*/
template <typename T1, typename T2>
inline constexpr std::pair<std::common_type_t<T1, T2>, std::common_type_t<T1, T2>> divmod(T1 a, T2 b) {
std::common_type_t<T1, T2> q = floordiv(a, b);
return {q, a - q * b};
}
/**
* 0 <= x < a
*/
inline constexpr bool inrange(long long x, long long a) {
return 0 <= x && x < a;
}
/**
* a <= x < b
*/
inline constexpr bool inrange(long long x, long long a, long long b) {
return a <= x && x < b;
}
/**
* 0 <= x < a and 0 <= y < b
*/
inline constexpr bool inrect(long long x, long long y, long long a, long long b) {
return 0 <= x && x < a && 0 <= y && y < b;
}
#line 15 "src/math/quotients.hpp"
/**
* @brief 商 q と、それをとる添字の区間 [l, r)
*/
struct QuotientRange {
long long q; //!< 商
long long l; //!< 区間の左端 (含む)
long long r; //!< 区間の右端 (含まない)
};
namespace internal_quotients {
struct Quotients {
long long n = 0;
QuotientRange current{0, 1, 1};
bool done = true;
void advance() {
const long long l = current.r;
done = l > n;
if (!done) {
const long long q = n / l;
current = {q, l, n / q + 1};
}
}
};
struct QuotientsLinear {
long long n = 0, m = 1, a = 0, b = 0;
QuotientRange current{0, 0, 0};
bool done = true;
void advance() {
const long long l = current.r;
done = l == n;
if (done) return;
if (a == 1) {
long long q, length;
if (l == 0) {
auto [initial_q, rem] = divmod(static_cast<__int128_t>(b), static_cast<__int128_t>(m));
q = static_cast<long long>(initial_q);
length = m - static_cast<long long>(rem);
} else {
assert(current.q < std::numeric_limits<long long>::max());
q = current.q + 1;
length = m;
}
current = {q, l, l + std::min(length, n - l)};
return;
}
advance_general(l);
}
// 加算だけで進む a == 1 の更新をインライン化しやすいよう、汎用計算を分ける。
void advance_general(long long l) {
const __int128_t slope = a;
auto [q, rem] = divmod(slope * l + b, static_cast<__int128_t>(m));
assert(std::numeric_limits<long long>::min() <= q && q <= std::numeric_limits<long long>::max());
__int128_t length = n - l;
// 正の傾きでは次の商に届くまで、負の傾きでは余りが負になるまで進む
if (a > 0) chmin(length, ceildiv(m - rem, slope));
if (a < 0) chmin(length, rem / (-slope) + 1);
current = {static_cast<long long>(q), l, l + static_cast<long long>(length)};
}
};
// イテレータが状態を所有するため、range の寿命や別の走査に依存しない。
template <class State>
class Enumeration {
State initial;
public:
explicit Enumeration(State initial) : initial(initial) {}
class iterator {
State state;
public:
using value_type = QuotientRange;
using difference_type = std::ptrdiff_t;
using reference = value_type;
using pointer = void;
using iterator_category = std::input_iterator_tag;
iterator() = default;
explicit iterator(State state) : state(state) { this->state.advance(); }
value_type operator*() const { return state.current; }
iterator& operator++() {
state.advance();
return *this;
}
iterator operator++(int) {
auto previous = *this;
++*this;
return previous;
}
bool operator==(const iterator& other) const {
if (state.done || other.state.done) return state.done == other.state.done;
return state.current.l == other.state.current.l;
}
bool operator!=(const iterator& other) const { return !(*this == other); }
};
iterator begin() const { return iterator(initial); }
iterator end() const { return iterator(); }
};
} // namespace internal_quotients
/**
* @brief floor(n / i) が一定の区間を添字の昇順 (商の降順) に遅延列挙する。全体 O(sqrt(n))、追加領域 O(1)
* @pre 0 <= n < std::numeric_limits<long long>::max()
*/
inline auto enumerate_quotients(long long n) {
assert(0 <= n && n < std::numeric_limits<long long>::max());
return internal_quotients::Enumeration(internal_quotients::Quotients{n});
}
/**
* @brief x = 0, ..., n - 1 を floor((a x + b) / m) の値で区間に分け、x の昇順に遅延列挙する。全体 O(区間数)、追加領域 O(1)
* @pre n >= 0、m >= 1、各商が long long に収まること。a, b は負でもよい
*/
inline auto enumerate_quotients_linear(long long n, long long m, long long a, long long b) {
assert(n >= 0 && m >= 1);
return internal_quotients::Enumeration(internal_quotients::QuotientsLinear{n, m, a, b});
}
/**
* @brief floor(n / i) が一定の区間ごとに f(q, l, r) を呼ぶ O(sqrt(n))
*/
template <typename F>
void for_each_quotient(long long n, F f) {
for (auto [q, l, r] : enumerate_quotients(n)) f(q, l, r);
}
/**
* @brief floor((a x + b) / m) が一定の区間ごとに f(q, l, r) を呼ぶ O(区間数)
*/
template <typename F>
void for_each_quotient_linear(long long n, long long m, long long a, long long b, F f) {
for (auto [q, l, r] : enumerate_quotients_linear(n, m, a, b)) f(q, l, r);
}