跳到正文

算法·理论

快速取模

luckydrawbox约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年2月25日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 1 分钟

版本

  1. v1当前
C++
struct FastMod
{
    using ull=unsigned long long;
    using L=__int128;
    ull b,m;
    // FastMod(ull b):b(b),m(ull((L(1)<<64)/b)){}
    FastMod(ull b1=1){
        b=b1;m=ull((L(1)<<64)/b1);
    }
    ull reduce(ull a)// return a mod b
    {
        ull q=(ull)((L(m)*a)>>64),r=a-q*b;
        return r>=b?r-b:r;
    }
}F;

预处理为 F=FastMod(mod),modmod 为模数,取模直接用 F.reduce(a) 得到 a%moda\%mod 的结果。

原文