shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: 有理数
(src/math/rational.hpp)

有理数 (分数) を誤差なく扱う Rational<T> です。T は整数型で、既定は long long です。値は常に既約で、分母は正です (0 は 0/1)。傾きや比を誤差なく比べたり、std::map や std::set のキーにしたりするのに使います。

using Q = Rational<>;
Q a(1, 3), b(1, 6);
Q c = a + b;               // 1/2
bool lt = a < b;           // false
Q d(2, -4);                // -1/2 (既約にして、分母を正にする)
std::set<Q> slopes;        // 傾きの種類を数える
slopes.insert(Q(dy, dx));  // dx != 0
std::cout << c << '\n';    // 1/2

メンバ関数

計算量の $p$、$q$ は分子・分母の絶対値です。

関数 説明 計算量
Rational(n = 0) 整数 n $O(1)$
Rational(num, den) num / den (den != 0)。既約にして分母を正にする $O(\log \max(\lvert p \rvert, q))$
num() / den() 分子 / 分母 (正) $O(1)$
+、- (単項・二項)、*、/、+=、-=、*=、/= 四則演算 (0 での割り算は assert で落ちる) $O(\log \max(\lvert p \rvert, q))$ (単項 - は $O(1)$)
==、!=、<、<=、>、>= 比較。整数とも比べられる (q < 1 など) $O(1)$ (T = __int128 の大小比較は $O(\log \max(\lvert p \rvert, q))$)
floor() / ceil() 以下で最大の整数 / 以上で最小の整数 $O(1)$
is_integer() 整数か $O(1)$
inv() / abs() 逆数 (0 でないこと) / 絶対値 $O(1)$
to_double() / to_long_double() / (double)q 浮動小数点数に直した値 $O(1)$
to_string() "p/q" の形の文字列 (整数なら "p") 桁数に比例
os << q / is >> q to_string() の形で出力 / "p/q" か "p" の形で入力 桁数に比例 (入力は既約にするので + $O(\log \max(\lvert p \rvert, q))$)

オーバーフローについて

関連

Depends on

Required by

Verified with

Code

#pragma once

/**
 * @file rational.hpp
 * @brief 有理数
 */

#include <cassert>
#include <cstddef>
#include <istream>
#include <ostream>
#include <string>
#include <utility>

#include "../base/functions.hpp"

/**
 * @brief 有理数 (分数)
 *
 * 常に既約で、分母は正。0 は 0/1
 * 演算の途中でも、既約にしてから掛けるのでオーバーフローしにくい。比較は T が 64 bit 以下なら __int128 で、そうでなければ連分数展開で行う
 * std::map や std::set のキーに使える
 * 例:
 * Rational<> a(1, 3), b(1, 6);
 * a + b;   // 1/2
 * a < b;   // false
 *
 * @tparam T 整数型 (long long や __int128 など)
 */
template <typename T = long long>
class Rational {
    T p, q;  // p / q (q > 0、gcd(p, q) = 1)

    static constexpr T abs_(T x) { return x < 0 ? -x : x; }
    static constexpr T gcd_(T a, T b) {
        a = abs_(a), b = abs_(b);
        while (b != 0) {
            T t = a % b;
            a = b;
            b = t;
        }
        return a;
    }
    struct Raw {};
    // すでに既約で q > 0 とわかっている場合
    constexpr Rational(T p, T q, Raw) : p(p), q(q) {}

    // a / b と c / d (b, d > 0) を比べ、小さければ負、等しければ 0、大きければ正を返す
    static constexpr int compare(T a, T b, T c, T d) {
        if constexpr (sizeof(T) <= 8) {
            __int128 x = static_cast<__int128>(a) * d, y = static_cast<__int128>(c) * b;
            return x < y ? -1 : x > y ? 1
                                      : 0;
        } else {
            // 整数部分を比べ、同じなら小数部分の逆数を比べる (大小が逆になる)
            int sign = 1;
            while (true) {
                T x = floordiv(a, b), y = floordiv(c, d);
                if (x != y) return x < y ? -sign : sign;
                a -= x * b, c -= y * d;
                if (a == 0 || c == 0) {
                    if (a == 0 && c == 0) return 0;
                    return a == 0 ? -sign : sign;
                }
                T t = a;
                a = b, b = t;
                t = c;
                c = d, d = t;
                sign = -sign;
            }
        }
    }

   public:
    /**
     * @brief 整数 n
     */
    constexpr Rational(T n = 0) : p(n), q(1) {}
    /**
     * @brief num / den (den != 0)
     */
    constexpr Rational(T num, T den) : p(num), q(den) {
        assert(den != 0 && "Rational: division by zero");
        if (q < 0) p = -p, q = -q;
        T g = gcd_(p, q);
        p /= g, q /= g;
    }

    /**
     * @brief 分子
     */
    constexpr T num() const { return p; }
    /**
     * @brief 分母 (正)
     */
    constexpr T den() const { return q; }

    /**
     * @brief 以下で最大の整数
     */
    constexpr T floor() const { return floordiv(p, q); }
    /**
     * @brief 以上で最小の整数
     */
    constexpr T ceil() const { return ceildiv(p, q); }
    /**
     * @brief 整数か
     */
    constexpr bool is_integer() const { return q == 1; }
    /**
     * @brief double に直した値
     */
    constexpr double to_double() const { return static_cast<double>(p) / static_cast<double>(q); }
    /**
     * @brief long double に直した値
     */
    constexpr long double to_long_double() const { return static_cast<long double>(p) / static_cast<long double>(q); }
    explicit constexpr operator double() const { return to_double(); }

    /**
     * @brief 逆数 (0 でないこと)
     */
    constexpr Rational inv() const {
        assert(p != 0 && "Rational: division by zero");
        return p > 0 ? Rational(q, p, Raw{}) : Rational(-q, -p, Raw{});
    }
    /**
     * @brief 絶対値
     */
    constexpr Rational abs() const { return Rational(abs_(p), q, Raw{}); }

    constexpr Rational operator+() const { return *this; }
    constexpr Rational operator-() const { return Rational(-p, q, Raw{}); }

    constexpr Rational& operator+=(const Rational& r) {
        // p / q + r.p / r.q を、分母の gcd で割ってから通分する
        T g = gcd_(q, r.q);
        T qg = q / g;
        T t = p * (r.q / g) + r.p * qg;
        T g2 = gcd_(t, g);
        p = t / g2;
        q = qg * (r.q / g2);
        return *this;
    }
    constexpr Rational& operator-=(const Rational& r) { return *this += -r; }
    constexpr Rational& operator*=(const Rational& r) {
        // 掛ける前に、分子と相手の分母の gcd で割る
        T g1 = gcd_(p, r.q), g2 = gcd_(r.p, q);
        p = (p / g1) * (r.p / g2);
        q = (q / g2) * (r.q / g1);
        return *this;
    }
    constexpr Rational& operator/=(const Rational& r) { return *this *= r.inv(); }

    friend constexpr Rational operator+(Rational a, const Rational& b) { return a += b; }
    friend constexpr Rational operator-(Rational a, const Rational& b) { return a -= b; }
    friend constexpr Rational operator*(Rational a, const Rational& b) { return a *= b; }
    friend constexpr Rational operator/(Rational a, const Rational& b) { return a /= b; }

    friend constexpr bool operator==(const Rational& a, const Rational& b) { return a.p == b.p && a.q == b.q; }
    friend constexpr bool operator!=(const Rational& a, const Rational& b) { return !(a == b); }
    friend constexpr bool operator<(const Rational& a, const Rational& b) { return compare(a.p, a.q, b.p, b.q) < 0; }
    friend constexpr bool operator>(const Rational& a, const Rational& b) { return b < a; }
    friend constexpr bool operator<=(const Rational& a, const Rational& b) { return !(b < a); }
    friend constexpr bool operator>=(const Rational& a, const Rational& b) { return !(a < b); }

    /**
     * @brief "p/q" の形の文字列 (整数なら "p")
     */
    std::string to_string() const {
        auto str = [](T x) {
            if (x == 0) return std::string("0");
            bool neg = x < 0;
            std::string s;
            // 負のまま 1 桁ずつ取り出す (最小値でもオーバーフローしない)
            while (x != 0) {
                T d = x % 10;
                s += static_cast<char>('0' + (d < 0 ? -d : d));
                x /= 10;
            }
            if (neg) s += '-';
            return std::string(s.rbegin(), s.rend());
        };
        return q == 1 ? str(p) : str(p) + "/" + str(q);
    }

    friend std::ostream& operator<<(std::ostream& os, const Rational& r) { return os << r.to_string(); }
    /**
     * @brief "p/q" または "p" の形で読む
     */
    friend std::istream& operator>>(std::istream& is, Rational& r) {
        std::string s;
        if (!(is >> s)) return is;
        auto parse = [](const std::string& t) {
            T x = 0;
            bool neg = false;
            std::size_t i = 0;
            if (i < t.size() && (t[i] == '-' || t[i] == '+')) neg = t[i++] == '-';
            for (; i < t.size(); i++) x = x * 10 + (t[i] - '0');
            return neg ? -x : x;
        };
        auto pos = s.find('/');
        if (pos == std::string::npos)
            r = Rational(parse(s));
        else
            r = Rational(parse(s.substr(0, pos)), parse(s.substr(pos + 1)));
        return is;
    }
};
#line 2 "src/math/rational.hpp"

/**
 * @file rational.hpp
 * @brief 有理数
 */

#include <cassert>
#include <cstddef>
#include <istream>
#include <ostream>
#include <string>
#include <utility>

#line 2 "src/base/functions.hpp"

/**
 * @file functions.hpp
 * @brief 汎用関数 (chmin, chmax など)
 */

#include <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <numeric>
#if __cplusplus >= 202002L
#include <ranges>
#endif
#include <type_traits>
#line 18 "src/base/functions.hpp"

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 16 "src/math/rational.hpp"

/**
 * @brief 有理数 (分数)
 *
 * 常に既約で、分母は正。0 は 0/1
 * 演算の途中でも、既約にしてから掛けるのでオーバーフローしにくい。比較は T が 64 bit 以下なら __int128 で、そうでなければ連分数展開で行う
 * std::map や std::set のキーに使える
 * 例:
 * Rational<> a(1, 3), b(1, 6);
 * a + b;   // 1/2
 * a < b;   // false
 *
 * @tparam T 整数型 (long long や __int128 など)
 */
template <typename T = long long>
class Rational {
    T p, q;  // p / q (q > 0、gcd(p, q) = 1)

    static constexpr T abs_(T x) { return x < 0 ? -x : x; }
    static constexpr T gcd_(T a, T b) {
        a = abs_(a), b = abs_(b);
        while (b != 0) {
            T t = a % b;
            a = b;
            b = t;
        }
        return a;
    }
    struct Raw {};
    // すでに既約で q > 0 とわかっている場合
    constexpr Rational(T p, T q, Raw) : p(p), q(q) {}

    // a / b と c / d (b, d > 0) を比べ、小さければ負、等しければ 0、大きければ正を返す
    static constexpr int compare(T a, T b, T c, T d) {
        if constexpr (sizeof(T) <= 8) {
            __int128 x = static_cast<__int128>(a) * d, y = static_cast<__int128>(c) * b;
            return x < y ? -1 : x > y ? 1
                                      : 0;
        } else {
            // 整数部分を比べ、同じなら小数部分の逆数を比べる (大小が逆になる)
            int sign = 1;
            while (true) {
                T x = floordiv(a, b), y = floordiv(c, d);
                if (x != y) return x < y ? -sign : sign;
                a -= x * b, c -= y * d;
                if (a == 0 || c == 0) {
                    if (a == 0 && c == 0) return 0;
                    return a == 0 ? -sign : sign;
                }
                T t = a;
                a = b, b = t;
                t = c;
                c = d, d = t;
                sign = -sign;
            }
        }
    }

   public:
    /**
     * @brief 整数 n
     */
    constexpr Rational(T n = 0) : p(n), q(1) {}
    /**
     * @brief num / den (den != 0)
     */
    constexpr Rational(T num, T den) : p(num), q(den) {
        assert(den != 0 && "Rational: division by zero");
        if (q < 0) p = -p, q = -q;
        T g = gcd_(p, q);
        p /= g, q /= g;
    }

    /**
     * @brief 分子
     */
    constexpr T num() const { return p; }
    /**
     * @brief 分母 (正)
     */
    constexpr T den() const { return q; }

    /**
     * @brief 以下で最大の整数
     */
    constexpr T floor() const { return floordiv(p, q); }
    /**
     * @brief 以上で最小の整数
     */
    constexpr T ceil() const { return ceildiv(p, q); }
    /**
     * @brief 整数か
     */
    constexpr bool is_integer() const { return q == 1; }
    /**
     * @brief double に直した値
     */
    constexpr double to_double() const { return static_cast<double>(p) / static_cast<double>(q); }
    /**
     * @brief long double に直した値
     */
    constexpr long double to_long_double() const { return static_cast<long double>(p) / static_cast<long double>(q); }
    explicit constexpr operator double() const { return to_double(); }

    /**
     * @brief 逆数 (0 でないこと)
     */
    constexpr Rational inv() const {
        assert(p != 0 && "Rational: division by zero");
        return p > 0 ? Rational(q, p, Raw{}) : Rational(-q, -p, Raw{});
    }
    /**
     * @brief 絶対値
     */
    constexpr Rational abs() const { return Rational(abs_(p), q, Raw{}); }

    constexpr Rational operator+() const { return *this; }
    constexpr Rational operator-() const { return Rational(-p, q, Raw{}); }

    constexpr Rational& operator+=(const Rational& r) {
        // p / q + r.p / r.q を、分母の gcd で割ってから通分する
        T g = gcd_(q, r.q);
        T qg = q / g;
        T t = p * (r.q / g) + r.p * qg;
        T g2 = gcd_(t, g);
        p = t / g2;
        q = qg * (r.q / g2);
        return *this;
    }
    constexpr Rational& operator-=(const Rational& r) { return *this += -r; }
    constexpr Rational& operator*=(const Rational& r) {
        // 掛ける前に、分子と相手の分母の gcd で割る
        T g1 = gcd_(p, r.q), g2 = gcd_(r.p, q);
        p = (p / g1) * (r.p / g2);
        q = (q / g2) * (r.q / g1);
        return *this;
    }
    constexpr Rational& operator/=(const Rational& r) { return *this *= r.inv(); }

    friend constexpr Rational operator+(Rational a, const Rational& b) { return a += b; }
    friend constexpr Rational operator-(Rational a, const Rational& b) { return a -= b; }
    friend constexpr Rational operator*(Rational a, const Rational& b) { return a *= b; }
    friend constexpr Rational operator/(Rational a, const Rational& b) { return a /= b; }

    friend constexpr bool operator==(const Rational& a, const Rational& b) { return a.p == b.p && a.q == b.q; }
    friend constexpr bool operator!=(const Rational& a, const Rational& b) { return !(a == b); }
    friend constexpr bool operator<(const Rational& a, const Rational& b) { return compare(a.p, a.q, b.p, b.q) < 0; }
    friend constexpr bool operator>(const Rational& a, const Rational& b) { return b < a; }
    friend constexpr bool operator<=(const Rational& a, const Rational& b) { return !(b < a); }
    friend constexpr bool operator>=(const Rational& a, const Rational& b) { return !(a < b); }

    /**
     * @brief "p/q" の形の文字列 (整数なら "p")
     */
    std::string to_string() const {
        auto str = [](T x) {
            if (x == 0) return std::string("0");
            bool neg = x < 0;
            std::string s;
            // 負のまま 1 桁ずつ取り出す (最小値でもオーバーフローしない)
            while (x != 0) {
                T d = x % 10;
                s += static_cast<char>('0' + (d < 0 ? -d : d));
                x /= 10;
            }
            if (neg) s += '-';
            return std::string(s.rbegin(), s.rend());
        };
        return q == 1 ? str(p) : str(p) + "/" + str(q);
    }

    friend std::ostream& operator<<(std::ostream& os, const Rational& r) { return os << r.to_string(); }
    /**
     * @brief "p/q" または "p" の形で読む
     */
    friend std::istream& operator>>(std::istream& is, Rational& r) {
        std::string s;
        if (!(is >> s)) return is;
        auto parse = [](const std::string& t) {
            T x = 0;
            bool neg = false;
            std::size_t i = 0;
            if (i < t.size() && (t[i] == '-' || t[i] == '+')) neg = t[i++] == '-';
            for (; i < t.size(); i++) x = x * 10 + (t[i] - '0');
            return neg ? -x : x;
        };
        auto pos = s.find('/');
        if (pos == std::string::npos)
            r = Rational(parse(s));
        else
            r = Rational(parse(s.substr(0, pos)), parse(s.substr(pos + 1)));
        return is;
    }
};
Back to top page