shogo-library

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

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/math/rational.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// Rational を、__int128 で通分して計算する愚直な方法とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#include "../../../src/math/rational.hpp"

#include <iostream>
#include <map>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <vector>

using i128 = __int128;

i128 gcd128(i128 a, i128 b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b) {
        i128 t = a % b;
        a = b;
        b = t;
    }
    return a;
}

// p / q を既約にして Rational<T> と一致するか
template <typename T>
bool same(const Rational<T>& r, i128 p, i128 q) {
    if (q < 0) p = -p, q = -q;
    i128 g = gcd128(p, q);
    return static_cast<i128>(r.num()) == p / g && static_cast<i128>(r.den()) == q / g;
}

template <typename T>
bool test(std::mt19937_64& rng, long long range) {
    bool ok = true;
    auto rnd = [&](bool nonzero) {
        while (true) {
            long long x = static_cast<long long>(rng() % (2 * range + 1)) - range;
            if (!nonzero || x != 0) return x;
        }
    };
    for (int rep = 0; rep < 100000 && ok; rep++) {
        long long a = rnd(false), b = rnd(true), c = rnd(false), d = rnd(true);
        Rational<T> x(a, b), y(c, d);
        ok = ok && same(x, a, b) && x.den() > 0;
        ok = ok && same(x + y, static_cast<i128>(a) * d + static_cast<i128>(c) * b, static_cast<i128>(b) * d);
        ok = ok && same(x - y, static_cast<i128>(a) * d - static_cast<i128>(c) * b, static_cast<i128>(b) * d);
        ok = ok && same(x * y, static_cast<i128>(a) * c, static_cast<i128>(b) * d);
        if (c != 0) ok = ok && same(x / y, static_cast<i128>(a) * d, static_cast<i128>(b) * c);
        // 比較
        int sgn = (b > 0) == (d > 0) ? 1 : -1;
        i128 l = static_cast<i128>(a) * d * sgn, r = static_cast<i128>(c) * b * sgn;
        ok = ok && (x < y) == (l < r) && (x == y) == (l == r) && (x <= y) == (l <= r) && (x > y) == (l > r);
        // floor, ceil
        long long fl = a / b, rem = a % b;
        if (rem != 0 && ((rem < 0) != (b < 0))) fl--;
        ok = ok && static_cast<long long>(x.floor()) == fl && static_cast<long long>(x.ceil()) == fl + (rem != 0);
        ok = ok && x.is_integer() == (rem == 0);
        // 文字列にして読み直す
        std::stringstream ss;
        ss << x;
        Rational<T> z;
        ss >> z;
        ok = ok && z == x;
    }
    return ok;
}

int main() {
    std::mt19937_64 rng(314);
    bool ok = true;
    ok = ok && test<long long>(rng, 20);
    ok = ok && test<long long>(rng, 1000000000);
    ok = ok && test<int>(rng, 30000);
    ok = ok && test<__int128>(rng, 20);
    ok = ok && test<__int128>(rng, 1000000000000000000LL);

    // __int128 で、通分すると 128 bit に収まらない値どうしの比較 (連分数展開で比べる)
    {
        using R = Rational<__int128>;
        i128 big = static_cast<i128>(1) << 100;
        R x(big + 1, big), y(big + 2, big + 1);  // 1 + 1/big > 1 + 1/(big+1)
        ok = ok && y < x && !(x < y) && x != y && R(big, 3) > R(big - 1, 3);
        ok = ok && R(-big, big + 1) < R(-big + 1, big) && R(-(big + 1), 7).floor() == -(big + 1) / 7 - 1;
    }

    // 例
    using Q = Rational<>;
    ok = ok && Q(1, 3) + Q(1, 6) == Q(1, 2) && Q(2, -4) == Q(-1, 2) && Q(0, -5) == Q(0);
    ok = ok && Q(3, 2) * 2 == 3 && 1 < Q(3, 2) && Q(-7, 2).floor() == -4 && Q(-7, 2).ceil() == -3;
    ok = ok && Q(-3, 4).inv() == Q(-4, 3) && Q(-3, 4).abs() == Q(3, 4) && -Q(1, 2) == Q(-1, 2);
    ok = ok && Q(1, 3).to_string() == "1/3" && Q(-6, 3).to_string() == "-2" && Q(1, 4).to_double() == 0.25;
    // map や set のキーにできる (傾きを数える)
    std::set<Q> slopes = {Q(1, 2), Q(2, 4), Q(-1, 3), Q(3, -9)};
    ok = ok && slopes.size() == 2 && *slopes.begin() == Q(-1, 3);
    std::map<Q, int> mp;
    mp[Q(2, 6)]++, mp[Q(1, 3)]++;
    ok = ok && mp[Q(1, 3)] == 2;
    // 入力の形式
    std::stringstream ss("3/6 -4 +5/-10");
    Q a, b, c;
    ss >> a >> b >> c;
    ok = ok && a == Q(1, 2) && b == Q(-4) && c == Q(-1, 2);

    if (ok)
        std::cout << "Hello World" << std::endl;
    else
        std::cerr << "failed" << std::endl;
}
#line 1 "test/unittest/math/rational.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// Rational を、__int128 で通分して計算する愚直な方法とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#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;
    }
};
#line 7 "test/unittest/math/rational.test.cpp"

#include <iostream>
#include <map>
#include <random>
#include <set>
#include <sstream>
#line 14 "test/unittest/math/rational.test.cpp"
#include <vector>

using i128 = __int128;

i128 gcd128(i128 a, i128 b) {
    if (a < 0) a = -a;
    if (b < 0) b = -b;
    while (b) {
        i128 t = a % b;
        a = b;
        b = t;
    }
    return a;
}

// p / q を既約にして Rational<T> と一致するか
template <typename T>
bool same(const Rational<T>& r, i128 p, i128 q) {
    if (q < 0) p = -p, q = -q;
    i128 g = gcd128(p, q);
    return static_cast<i128>(r.num()) == p / g && static_cast<i128>(r.den()) == q / g;
}

template <typename T>
bool test(std::mt19937_64& rng, long long range) {
    bool ok = true;
    auto rnd = [&](bool nonzero) {
        while (true) {
            long long x = static_cast<long long>(rng() % (2 * range + 1)) - range;
            if (!nonzero || x != 0) return x;
        }
    };
    for (int rep = 0; rep < 100000 && ok; rep++) {
        long long a = rnd(false), b = rnd(true), c = rnd(false), d = rnd(true);
        Rational<T> x(a, b), y(c, d);
        ok = ok && same(x, a, b) && x.den() > 0;
        ok = ok && same(x + y, static_cast<i128>(a) * d + static_cast<i128>(c) * b, static_cast<i128>(b) * d);
        ok = ok && same(x - y, static_cast<i128>(a) * d - static_cast<i128>(c) * b, static_cast<i128>(b) * d);
        ok = ok && same(x * y, static_cast<i128>(a) * c, static_cast<i128>(b) * d);
        if (c != 0) ok = ok && same(x / y, static_cast<i128>(a) * d, static_cast<i128>(b) * c);
        // 比較
        int sgn = (b > 0) == (d > 0) ? 1 : -1;
        i128 l = static_cast<i128>(a) * d * sgn, r = static_cast<i128>(c) * b * sgn;
        ok = ok && (x < y) == (l < r) && (x == y) == (l == r) && (x <= y) == (l <= r) && (x > y) == (l > r);
        // floor, ceil
        long long fl = a / b, rem = a % b;
        if (rem != 0 && ((rem < 0) != (b < 0))) fl--;
        ok = ok && static_cast<long long>(x.floor()) == fl && static_cast<long long>(x.ceil()) == fl + (rem != 0);
        ok = ok && x.is_integer() == (rem == 0);
        // 文字列にして読み直す
        std::stringstream ss;
        ss << x;
        Rational<T> z;
        ss >> z;
        ok = ok && z == x;
    }
    return ok;
}

int main() {
    std::mt19937_64 rng(314);
    bool ok = true;
    ok = ok && test<long long>(rng, 20);
    ok = ok && test<long long>(rng, 1000000000);
    ok = ok && test<int>(rng, 30000);
    ok = ok && test<__int128>(rng, 20);
    ok = ok && test<__int128>(rng, 1000000000000000000LL);

    // __int128 で、通分すると 128 bit に収まらない値どうしの比較 (連分数展開で比べる)
    {
        using R = Rational<__int128>;
        i128 big = static_cast<i128>(1) << 100;
        R x(big + 1, big), y(big + 2, big + 1);  // 1 + 1/big > 1 + 1/(big+1)
        ok = ok && y < x && !(x < y) && x != y && R(big, 3) > R(big - 1, 3);
        ok = ok && R(-big, big + 1) < R(-big + 1, big) && R(-(big + 1), 7).floor() == -(big + 1) / 7 - 1;
    }

    // 例
    using Q = Rational<>;
    ok = ok && Q(1, 3) + Q(1, 6) == Q(1, 2) && Q(2, -4) == Q(-1, 2) && Q(0, -5) == Q(0);
    ok = ok && Q(3, 2) * 2 == 3 && 1 < Q(3, 2) && Q(-7, 2).floor() == -4 && Q(-7, 2).ceil() == -3;
    ok = ok && Q(-3, 4).inv() == Q(-4, 3) && Q(-3, 4).abs() == Q(3, 4) && -Q(1, 2) == Q(-1, 2);
    ok = ok && Q(1, 3).to_string() == "1/3" && Q(-6, 3).to_string() == "-2" && Q(1, 4).to_double() == 0.25;
    // map や set のキーにできる (傾きを数える)
    std::set<Q> slopes = {Q(1, 2), Q(2, 4), Q(-1, 3), Q(3, -9)};
    ok = ok && slopes.size() == 2 && *slopes.begin() == Q(-1, 3);
    std::map<Q, int> mp;
    mp[Q(2, 6)]++, mp[Q(1, 3)]++;
    ok = ok && mp[Q(1, 3)] == 2;
    // 入力の形式
    std::stringstream ss("3/6 -4 +5/-10");
    Q a, b, c;
    ss >> a >> b >> c;
    ok = ok && a == Q(1, 2) && b == Q(-4) && c == Q(-1, 2);

    if (ok)
        std::cout << "Hello World" << std::endl;
    else
        std::cerr << "failed" << std::endl;
}
Back to top page