快速取模

· · 算法·理论

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),mod 为模数,取模直接用 F.reduce(a) 得到 a\%mod 的结果。