跳到正文

个人记录

【模板】运行时Montgomery及其评测

dengyaotriangle约 13 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年6月8日
篇幅
约 13 分钟
获赞
2

版本

  1. v1当前

瞎搓的一个模板

提供类型:mont30_t mont31_t mont62_t mont63_t

mont[B]_t 可以加速 x<2Bx<2^B 的奇数 xx ,  mod  x\bmod\ x 上的运算。

使用方法:

默认模数是 998244353998244353,可以按需更改

对于一个合法的模数 xx ,首先构造一个 montctx32_t(x) 或 montctx64_t(x),然后使用 mont[B]_t::setctx() 传入 montctx_t 即可。

亦可以使用 mont[B]_t::getctx() 获取当前设置的模数的信息

montctx_t 可以理解为一个模数所需的预处理信息。

支持加减乘除和取负,以及和对应类型的普通整数的类型转化,相等和不能的判断,以及输入输出。

需要注意的是,若将一个数 uu 转化成模 xx 的数,并不需要考虑 u≥xu\geq x,任何32位(或64位)的数都是可以正确转化的。所以不需要预先取模。

所以这玩意还可以直接拿来判断整除(

实现:

求逆元使用了牛顿迭代,应该构造 montctx_t 的常数也蛮小的。

mont30_t 和 mont62_t 实际上过程中有些时候 %mdn 有些时候 %(2*mdn),这样可以避免一次 redc 后的判断,但代价是模数范围少一位。而 mont31_t 和 mont63_t 则不加这个优化。

测速对比:10001000 次随机模数,求 106!10^6!(实现:每次 +1+1 然后相乘),g++-11 -O2,64 位,~4.5GHz。

  • mont30_t:2.712.71 s
  • mont31_t:2.952.95 s
  • mont62_t:3.043.04 s
  • mont63_t:3.243.24 s
  • 朴素32位乘法取模:8.708.70 s
  • 朴素64位乘法取模:52.5352.53 s (朴素 __int128 取模真心慢,好像编译器内部实现了一个类似高精度除法的东西)
  • 常数模数32位乘法取模(求一次 109!10^9!):3.353.35 s

可见这个东西可以让你在需要膜 long long 的时候提速超过10倍,其它时候也有一定的性能提升。

Montgomery 似乎模数是否是常数对性能的影响极小,所以懒得搞常量版本的了。(看,我模数不加 const 比你加了 const 还快!)

实战: 截止现在,luogu Pollard-Rho 模板拿下了最优解 (本来还想试试 QS,但是发现这个数据范围下我的垃圾 QS 实现完全没有 PR 快)

总代码:(可以从中按需抠出想要的部分)

C++
/*

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <https://unlicense.org>
*/
//# 30 31 62 63
template<typename T,typename UT> class montctx_t{
private:
    typedef T val_t;
    typedef UT mval_t;
    static const int tlen=sizeof(val_t)*8;
public:
    val_t mdn,mdn2,p2,r;
    montctx_t(val_t x):mdn(x),mdn2(x<<1),p2(-mval_t(mdn)%mdn),r(1){
        for(int i=1;i<tlen;i<<=1)r*=2+r*mdn;
    }
    inline val_t redc(mval_t x)const{return (x+(val_t(x)*r)*mval_t(mdn))>>tlen;}
    inline val_t redu(val_t x)const{return x>=mdn2?x-mdn2:x;}
    inline val_t reds(val_t x)const{return x>=mdn?x-mdn:x;}
};
//# 30 31
typedef montctx_t<uint32_t,uint64_t> montctx32_t;
//# 62 63
typedef montctx_t<uint64_t,unsigned __int128> montctx64_t;
//# 30 62
template<typename T,typename UT> class mont_t{
private:
    typedef T val_t;
    typedef UT mval_t;
    static montctx_t<T,UT> ctx;
    val_t v;
public:
    static montctx_t<T,UT> getctx(){return ctx;}
    static void setctx(const montctx_t<T,UT>&x){ctx=x;}
    
    explicit operator val_t()const{return ctx.reds(ctx.redc(v));}
    mont_t(val_t x){v=ctx.redc(x*(mval_t)ctx.p2);}
    mont_t(){}
    mont_t(const mont_t&a):v(a.v){}
    mont_t&operator+=(const mont_t&a){v=ctx.redu(v+a.v);return*this;}
    mont_t&operator-=(const mont_t&a){v=ctx.redu(v-a.v+ctx.mdn2);return*this;}
    mont_t&operator*=(const mont_t&a){v=ctx.redc(v*(mval_t)a.v);return*this;}
    mont_t&operator=(const mont_t&a){v=a.v;return*this;}
    mont_t operator+(const mont_t&a)const{return mont_t(*this)+=a;}
    mont_t operator-(const mont_t&a)const{return mont_t(*this)-=a;}
    mont_t operator*(const mont_t&a)const{return mont_t(*this)*=a;}
    mont_t operator-()const{mont_t r;r.v=(v?ctx.mdn2-v:0);return r;}
    bool operator==(const mont_t&a)const{return ctx.reds(v)==ctx.reds(a.v);}
    bool operator!=(const mont_t&a)const{return !(*this==a);}
    friend std::istream&operator>>(std::istream&s,mont_t&v){val_t tmp;s>>tmp;v=mont_t(tmp);return s;}
    friend std::ostream&operator<<(std::ostream&s,const mont_t&v){return s<<val_t(v);}
};
//# 30
typedef mont_t<uint32_t,uint64_t> mont30_t;
template<> montctx32_t mont30_t::ctx=montctx32_t(998244353);
//# 62
typedef mont_t<uint64_t,unsigned __int128> mont62_t;
template<> montctx64_t mont62_t::ctx=montctx64_t(998244353);
//# 31 63
template<typename T,typename UT> class mont_e_t{
private:
    typedef T val_t;
    typedef UT mval_t;
    static montctx_t<T,UT> ctx;
    val_t v;
public:
    static montctx_t<T,UT> getctx(){return ctx;}
    static void setctx(const montctx_t<T,UT>&x){ctx=x;}
    
    explicit operator val_t()const{return ctx.reds(ctx.redc(v));}
    mont_e_t(val_t x){v=ctx.reds(ctx.redc(x*(mval_t)ctx.p2));}
    mont_e_t(){}
    mont_e_t(const mont_e_t&a):v(a.v){}
    mont_e_t&operator+=(const mont_e_t&a){v=ctx.reds(v+a.v);return*this;}
    mont_e_t&operator-=(const mont_e_t&a){v=ctx.reds(v-a.v+ctx.mdn);return*this;}
    mont_e_t&operator*=(const mont_e_t&a){v=ctx.reds(ctx.redc(v*(mval_t)a.v));return*this;}
    mont_e_t&operator=(const mont_e_t&a){v=a.v;return*this;}
    mont_e_t operator+(const mont_e_t&a)const{return mont_e_t(*this)+=a;}
    mont_e_t operator-(const mont_e_t&a)const{return mont_e_t(*this)-=a;}
    mont_e_t operator*(const mont_e_t&a)const{return mont_e_t(*this)*=a;}
    mont_e_t operator-()const{mont_e_t r;r.v=(v?ctx.mdn-v:0);return r;}
    bool operator==(const mont_e_t&a)const{return v==a.v;}
    bool operator!=(const mont_e_t&a)const{return !(*this==a);}
    friend std::istream&operator>>(std::istream&s,mont_e_t&v){val_t tmp;s>>tmp;v=mont_e_t(tmp);return s;}
    friend std::ostream&operator<<(std::ostream&s,const mont_e_t&v){return s<<val_t(v);}
};
//# 31
typedef mont_e_t<uint32_t,uint64_t> mont31_t;
template<> montctx32_t mont31_t::ctx=montctx32_t(998244353);
//# 63
typedef mont_e_t<uint64_t,unsigned __int128> mont63_t;
template<> montctx64_t mont63_t::ctx=montctx64_t(998244353);
//#

用于按需拷贝的脚本 (python)

python3
f=open("mont_template.cpp","r")

of = open("mont.cpp","w")

list =f.readlines()

needed = [ '62' ] # here

cur = []
for line in list:
    wline=line.split()
    if len(wline)>=1 and wline[0]=='//#':
        cur = wline
    else:
        ok = False
        for x in needed:
            if cur.count(x) > 0:
                ok=True

        if ok:
            print(line,end='',file=of)
原文
存档评论3 条抓取于