当前位置: 首页 > news >正文

分数运算类

分数运算类

定义了分数的四则运算,如果需要处理浮点数,那么需要将函数中的 gcd 运算替换为 fgcd

template<class T> struct Frac {T x, y;Frac() : Frac(0, 1) {}Frac(T x_) : Frac(x_, 1) {}Frac(T x_, T y_) : x(x_), y(y_) {if (y < 0) {y = -y;x = -x;}}constexpr double val() const {return 1. * x / y;}constexpr Frac norm() const { // 调整符号、转化为最简形式T p = gcd(x, y);return {x / p, y / p};}friend constexpr auto &operator<<(ostream &o, const Frac &j) {T p = gcd(j.x, j.y);if (j.y == p) {return o << j.x / p;} else {return o << j.x / p << "/" << j.y / p;}}constexpr Frac &operator/=(const Frac &i) {x *= i.y;y *= i.x;if (y < 0) {x = -x;y = -y;}return *this;}constexpr Frac &operator+=(const Frac &i) { return x = x * i.y + y * i.x, y *= i.y, *this; }constexpr Frac &operator-=(const Frac &i) { return x = x * i.y - y * i.x, y *= i.y, *this; }constexpr Frac &operator*=(const Frac &i) { return x *= i.x, y *= i.y, *this; }friend constexpr Frac operator+(const Frac i, const Frac j) { return i += j; }friend constexpr Frac operator-(const Frac i, const Frac j) { return i -= j; }friend constexpr Frac operator*(const Frac i, const Frac j) { return i *= j; }friend constexpr Frac operator/(const Frac i, const Frac j) { return i /= j; }friend constexpr Frac operator-(const Frac i) { return Frac(-i.x, i.y); }friend constexpr bool operator<(const Frac i, const Frac j) { return i.x * j.y < i.y * j.x; }friend constexpr bool operator>(const Frac i, const Frac j) { return i.x * j.y > i.y * j.x; }friend constexpr bool operator==(const Frac i, const Frac j) { return i.x * j.y == i.y * j.x; }friend constexpr bool operator!=(const Frac i, const Frac j) { return i.x * j.y != i.y * j.x; }
};
http://www.jsqmd.com/news/21207/

相关文章:

  • 坐标压缩与离散化
  • 撸一个功能强大的基于语义的图像检索系统
  • 提交一张 PPT,参与 RTE2025 全球语音智能体云展示
  • 完整教程:深入解析AppCrawler:开源自动遍历测试工具配置指南
  • 解释 EIP-4337
  • 数论常见结论及例题
  • 材料包含与下载漏洞
  • N8N Workflow Collection - 专业级自动化工作流库 - 详解
  • 完整教程:Elasticsearch面试精讲 Day 23:安全认证与权限控制
  • Min25 筛
  • 莫比乌斯函数/反演
  • 同余方程组、拓展中国剩余定理 excrt
  • 完整教程:微软2025教育AI报告:教育群体采用AI的比例显著提升
  • 求解连续数字的正约数集合——倍数法
  • 扩展欧几里得 exgcd
  • 离散对数 bsgs 与 exbsgs
  • 防爆模乘
  • 欧拉筛(线性筛)
  • 常见数列
  • 20232314 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • 【LTDC】LTDC 简介
  • Markdown数学公式 - -一叶知秋
  • 分类器案例 - -一叶知秋
  • 最大流
  • 最小割树 Gomory-Hu Tree
  • 最小割
  • 费用流
  • 图论常见结论及例题
  • 查询GPIO状态值(步骤)
  • 最长路(topsort+DP算法)