高精度整数模板

· · 个人记录

Fixed / BigInt 使用手册

Fixed:高精度定点数,覆盖整数与小数。 BigInt:高精度整数,API 更简洁。

选择建议:只做整数运算用 BigInt;涉及小数、需要保留小数位或截断用 Fixed。

保证数据十进制下位数 \le 10^7 时精度可控。

复杂度记号:全文用 N 表示十进制位数,M(N) 表示两个 N 位数相乘的复杂度,按规模分三段:

M(N)= \begin{cases} O(N^2), & N\le 500 \\ O(N\log N), & 500 < N \le 1.6\times 10^7 \\ O\!\left(\dfrac{N^2}{W}\log N\right), & N > 1.6\times 10^7,\text W=1.6\times 10^7 \end{cases}

:::success[一、构造对象]

1.1 Fixed 的四种构造

写法 结果 说明 复杂度
Fixed a; 0 零 O(1)
Fixed b(123); 123 整数 O(N)
Fixed d("789.012"); 789.012 小数用字符串 ^
Fixed::fromDouble(1.5) 1.5 显式浮点 + 块数 ^
Fixed::fromIntExp(1ll,100) 10^{800} 为 100 块 ^
Fixed a;                    // 0
Fixed b(123);               // 123
Fixed c(-456);              // -456
Fixed d("789.012");         // 789.012
Fixed e("-3.14");           // -3.14
Fixed f = Fixed::fromDouble(1.5L);   // 1.5
Fixed g = Fixed::fromIntExp(1LL, 100); // 10^800

记法:小数用字符串;浮点构造已 delete,需用 Fixed::fromDouble;放大整数用 Fixed::fromIntExp。

1.2 科学计数法

Fixed("1e10");       // 10000000000
Fixed("1.5e-3");     // 0.0015
Fixed("-2.5e5");     // -250000
Fixed("1E5");        // 100000(大写 E 也支持)
Fixed("0e5");        // 0

指数范围过大抛 runtime_error。复杂度 O(N)。

1.3 BigInt 的构造

BigInt a;                         // 0
BigInt b(123);                    // 123
BigInt d("12345678901234567890"); // 大整数
BigInt("1.5") 抛 runtime_error。复杂度 O(N)。

:::success[二、四则运算]

2.1 加减乘

运算 复杂度 1000 位 10^5 位 10^6 位 10^7 位
+、- O(N) < 0.01 ms < 1 ms 约 6-10 ms /
* O(M(N)) 0.08 ms 9.56 ms 92.4 ms 1805 ms
Fixed x("1.2"), y("3.4");
Fixed sum  = x + y;    // 4.6
Fixed diff = x - y;    // -2.2
Fixed prod = x * y;    // 4.08
BigInt q = BigInt("100") * BigInt("7");   // 700

M(N) 的定义见文首。

2.2 除法

运算 复杂度 50000/5000 位 10^5/10^4 位 10^6/10^5 位 2\times10^6/10^6位
a / b O(M(N)\log N) 19.2 ms 42.8 ms 450.5 ms 1239 ms

/ 是高精度除法,默认保留足够位数:

Fixed("10") / Fixed("3");      // 3.333...
BigInt("10") / BigInt("3");    // 3(整除)

divide(b, k) 控制保留位数,k 单位是位:

Fixed("1").divide(Fixed("3"), 8);    // 0.33333333
Fixed("2").divide(Fixed("3"), 8);    // 0.66666667(四舍五入)
Fixed("5").divide(Fixed("2"), 0);    // 3

2.3 带余除法:div_mod(b)

auto qr = Fixed("-10").div_mod(Fixed("3"));
// qr.first = -3(商),qr.second = -1(余数)

返回值 pair<Fixed,Fixed>。

满足 a = Q·b + R,|R| < |b|。复杂度 O(M(N)\log N)。

2.4 求余数

Fixed r1 = Fixed("10") % Fixed("3");   // Fixed,值为 1
long long r2 = Fixed("10") % 3;         // long long,值为 1

复杂度同除法。

2.5 与整数运算

Fixed z("1.5");
z = z * 6;      // 9
z = z / 3;      // 0.5
BigInt w("100");
w = w / 3;      // 33
w = w % 7;      // 2

* long long 是 O(N) 乘法。

2.6 整数在左的运算

5 - Fixed("10");     // -5
5 / Fixed("10");     // 0.5
10 % Fixed("3");     // Fixed("1")
3 * BigInt("100");   // 300

修改后暂不支持,可暂时显式构造来替代。

2.7 复合赋值

+=、-=、*=、/=、%= 均支持,复杂度同对应二元运算。

:::info[三、比较与判断]

Fixed x("1.23"), y("1.24");
bool lt = (x < y);      // true
BigInt a("-10"), b("1");
bool neg_lt = (a < b);  // true

复杂度 O(N)。

:::

:::warning[四、精度控制与截断]

4.1 截断到块:trunc(k)

⚠️ trunc(k) 的 k 单位是块(8 位小数),不是位。

Fixed x("3.14159265358979");
x.trunc(-1);   // 保留 1 块 = 8 位小数:3.14159265
x.trunc(0);    // 截断为 3

复杂度 O(N)。

4.2 按位数舍入 / 截断

Fixed("3.14159265").roundToDigits(4);   // 3.1416(四舍五入)
Fixed("3.14159265").truncToDigits(4);   // 3.1415(直接截断)

复杂度 O(N)。

4.3 四者的关系

方法 作用 单位 舍入方向
divide(b, k) 计算除法并保留 k 位 位 四舍五入
trunc(k) 截断当前值到 k 块 块(8 位) 直接截断
roundToDigits(k) 舍入到 k 位 位 四舍五入
truncToDigits(k) 截断到 k 位 位 直接截断

:::

:::success[五、数学函数]

5.1 快速幂:qpow(b)

Fixed("2").qpow(10);       // 1024
BigInt("2").qpow(100);     // 2^100

指数非负,否则抛 runtime_error。复杂度 O(\log b \cdot M(N))。

5.2 绝对值:abs()

复杂度 O(N)。

5.3 开平方:Fixed::sqrt(prec)

prec 单位是位。复杂度 O(M(N)\log N)。

精度 时间
100 位 0.041 ms
1000 位 1.00 ms
10^4 位 17.9 ms
10^5 位 280 ms
5\times 10^5位 1489 ms
Fixed("2").sqrt(100).write(100);   // √2 保留 100 位
Fixed("0.25").sqrt(20);            // 0.5

默认精度(prec = -1):\text{prec} = \text{输入位数的一半} + 16。

5.4 整数平方根:BigInt::sqrt()

返回向下取整的整数平方根。复杂度 O(M(N)\log N)。

BigInt("100").sqrt();   // 10
BigInt("10").sqrt();    // 3(向下取整)

实测:4000 位输入 10.7 ms。

5.5 取整

函数 语义 -2.5 2.5 复杂度
trunc(0) 向零截断 -2 2 O(N)
floor() 向下取整 -3 2 ^
ceil() 向上取整 -2 3 ^
round() 四舍五入 -3 3 ^

:::

:::info[六、类型转换]

6.1 to_ll()

复杂度 O(N)。超出 long long 范围溢出。

6.2 to_double()

复杂度 O(N)。

6.3 digit_count()

返回整数部分位数,|值| < 1 返回 0。复杂度 O(N)。

Fixed("0").digit_count();      // 0
Fixed("123.456").digit_count();// 3

6.4 真实指数:exponent()

返回数的真实 10 的幂次(x = m × 10^e,m \in [1, 10)),返回 long long。复杂度 O(N)。

Fixed("1e10").exponent();         // 10
Fixed("20959.155").exponent();    // 4
Fixed("0.001").exponent();        // -3
Fixed(1LL, 10^8).exponent();      // 800000000(1 块访问,O(1))
Fixed("0").exponent();            // 抛异常

:::

:::info[七、进制转换] BigInt 支持二进制和十六进制。复杂度 O(N^2)。

BigInt("255").toBinary();      // "11111111"
BigInt("255").toHex();         // "FF"
BigInt::fromHex("FF");         // 255

:::

::::success[八、输入输出]

8.1 流式 I/O

Fixed a, b;
cin >> a >> b; // 等价于 read()
cout << (a / b) << '\n';   // 等价 write() / write_auto(20)

BigInt 同理。

8.2 write() 三种输出模式

Fixed 的 write 有 5 个重载,分别对应 auto / exact / scientific:

调用 模式 说明
write() auto 指数在 [-100,100] 内按 20 位小数;否则 20 位有效数字科学计数法
write(k) auto 指数在 [-100,100] 内按 k 位小数;否则 k 位有效数字科学计数法
write_exact() exact 完整精确表示,不去尾零
write_exact(k) exact 精确到 k 位小数
write_scientific(sig) scientific 科学计数法,sig 位有效数字,默认 20
Fixed a("1.01");
a.qpow(1000);
a.write();              // 指数在范围内:保留 20 位小数
a.write(10);            // 保留 10 位小数
a.write_scientific(10); // 10 位有效数字科学计数法

Fixed b("0.5");
b.qpow(1000);           // 约 9.3326361850321887899e-302
b.write();              // 科学计数法
b.write_exact(100);     // 精确到 100 位小数

Fixed c = Fixed::fromIntExp(1LL, 100000); // 10^800000
c.write();              // "1e+800000"
c.write_scientific(10); // "1e+800000"
// c.write_exact();     // 会试图输出 80 万字符,慎用

:::warning[write(k) 与 write_exact(k) 的区别:]{open} 当指数在 [-100,100] 内,write(k) 与 write_exact(k) 都表示保留 k 位小数;当指数超出该范围,write(k) 转为 k 位有效数字的科学计数法,而 write_exact(k) 仍按精确小数位输出。 :::

BigInt 只有 write()(完整整数),不支持科学计数法。

8.3 read()

Fixed x;
x.read();       // 从 stdin 读一个空白分隔 token,再按 Fixed 字符串规则解析

BigInt::read() 同理,但只接受整数字符串;解析失败返回 false。

8.4 to_string() / to_scientific()

与 write 对应的字符串版本:

方法 等价于
to_string() write_exact() 的字符串版本
to_string(k) write_exact(k) 的字符串版本
to_scientific(sig) write_scientific(sig) 的字符串版本
to_auto(sig) write(sig) 的字符串版本
string s1 = Fixed("2.5").to_string(2);        // "2.50"
string s2 = Fixed("2.5").to_scientific(10);   // "2.5e+0"
string s3 = Fixed("20959.155").to_auto(10);   // 小范围下约等于保留 10 位小数

::::

:::info[九、测试场景]

9.1 大整数阶乘

BigInt fact(1);
for (int i = 1; i <= 1000; ++i) fact *= BigInt(i);
fact.write();

复杂度 O(n \cdot M(N))。1000! = 2568 位约 4.78 ms。

9.2 用 Machin 公式算 π

精度 时间
100 位 1.60 ms
1000 位 193 ms
Fixed pi_machin(int need){
    int wn = need + 16, wnb = (wn + 7) / 8;
    auto atan_inv = [&](long long x) -> Fixed {
        Fixed t = Fixed(1).divide(Fixed(x), wn);
        Fixed x2 = t * t, sum = t;
        for (long long n = 1; ; ++n) {
            t = (t * x2).trunc(-wnb);
            if (t == Fixed(0)) break;
            Fixed d = t.divide(Fixed(2*n+1), wn);
            if (d == Fixed(0)) break;
            sum = (n & 1) ? sum - d : sum + d;
        }
        return sum;
    };
    int needb = (need + 7) / 8;
    return (Fixed(16)*atan_inv(5) - Fixed(4)*atan_inv(239)).trunc(-needb);
}

9.3 判断完全平方数

BigInt n("123456789012345678901234567890");
bool is_square = (n.sqrt() * n.sqrt() == n);

:::

:::info[十、行为约定]

:::error[十一、已知限制与常见错误]{open} | 限制 | 对策 | | :--- | :--- | | Fixed(1.5) 编译错误 | 用 Fixed("1.5") 或 Fixed::fromDouble(1.5) | | Fixed(1, 100) 编译错误 | 写 Fixed::fromIntExp(1ll, 100) | | trunc(k) 单位是块 | 用 divide(b, k) 或 roundToDigits | | write(80) 后面补零 | 用 divide(b, 80) | | LLONG_MIN 做除数 UB | 极少触发 | | static 缓存非线程安全 | 单线程使用安全 | | to_ll() 溢出 | 调用方保证值域 | | to_double() 溢出 | 用 to_string |

错误写法对照:

// ❌
Fixed a(1.5);              // 编译错误:浮点构造已删除
Fixed b(1, 100);           // 编译错误:没有双参数构造
d.write(80);               // 小范围内会按 80 位小数补零
x.trunc(8);                // 8 个块,即 64 位小数,不是 8 位

// ✅
Fixed a = Fixed::fromDouble(1.5L); // 或 Fixed a("1.5");
Fixed b = Fixed::fromIntExp(1LL, 100);
Fixed d = Fixed("1").divide(Fixed("1.4"), 80);
x.trunc(-1);               // 8 位小数

:::

:::info[十二、性能参考] x86-64,3–4 GHz,-O2,完整 159365 项测试 0 FAIL。

12.1 乘法(对应 M(N) 的前三段)

位数 路径 时间 复杂度
500 朴素乘法 < 0.1 ms O(N^2)
1000 FFT 单次 0.078 ms O(N\log N)
10^4 ^ 0.93 ms ^
10^5 ^ 9.56 ms ^
2×10^5 ^ 19.5 ms ^
5×10^5 ^ 43.3 ms ^
10^6 ^ 92.4 ms ^
10^7 ^ 1805 ms ^

12.2 除法

规模 时间
50000/5000 19.2 ms
10^5/10^4 42.8 ms
10^6/10^5 450 ms
2\times 10^6/10^6 1239 ms

12.3 开方

规模 时间
sqrt 100 位 0.041 ms
sqrt 1000 位 1.00 ms
sqrt 10^4 位 17.9 ms
sqrt 10^5 位 280 ms
sqrt 5\times10^5 位 1489 ms
BigInt::sqrt 4000 位输入 10.7 ms

12.4 其他

操作 时间
2000! (5736 位) 3.7 ms
π 100 位 1.60 ms
π 1000 位 193 ms

:::

:::success[十三、快速索引]{open} | 需求 | 调用 | 复杂度 | | :--- | :--- | :--- | | 构造小数 | Fixed("1.5") 或 Fixed::fromDouble(1.5) | O(N) | | 构造放大整数 | Fixed::fromIntExp(1LL, 100) | ^ | | 构造科学计数法 | Fixed("1e10") |^| | 加法/减法 | a + b、a - b | ^ | | 乘法 | a * b | O(M(N)) | | 整数在左的运算 | 5 - x、5 * x |同对应运算 | | 除法 | a / b、a.divide(b, k) | O(M(N)\log N) | | 带余除法 | a.div_mod(b) | ^ | | 数学余数 | a % b | ^ | | 整数余数 | a % n | ^ | | 截断到 k 块小数 | a.trunc(-k) | O(N) | | 按位数舍入 | a.roundToDigits(k) | ^ | | 按位数截断 | a.truncToDigits(k) | ^ | | 显示 k 位小数 | a.write(k) | ^ | | 快速幂 | a.qpow(b) | O(\log b \cdot M(N)) | | 绝对值 | a.abs() | O(N) | | 开平方(带精度) | a.sqrt(k) | O(M(N)\log N) | | 整数平方根 | a.sqrt()(BigInt) | ^ | | 取整 | a.floor() / a.ceil() / a.round() | O(N) | | 转 long long | a.to_ll() | ^ | | 转 double | a.to_double() | ^ | | 整数部分位数 | a.digit_count() | ^ | | 转二进制/十六进制 | a.toBinary() / a.toHex() | O(N^2) | | 从二进制/十六进制构造 | BigInt::fromBinary(s) / fromHex(s) | ^ | | 流式 I/O | cin >> a; cout << a; | O(N) | | 转字符串 | a.to_string() / a.to_string(k) | O(N) | :::

:::info[Code] 共 430 行,约 25.8k。附带计算 \pi 代码。


#include<bits/stdc++.h>
using namespace std;
const double PI=acos(-1.0);
struct Fixed{
    struct FastInput{
        static const int SZ=1<<16;
        static char* buf(){static char b[SZ];return b;}
        static int& p(){static int x=0;return x;}
        static int& len(){static int y=0;return y;}
        static int getChar(){char*b=buf();int&x=p(),&y=len();if(x==y){y=(int)fread(b,1,SZ,stdin);x=0;if(y<=0)return EOF;}return (unsigned char)b[x++];}
        static void ungetChar(){int&x=p();if(x>0)--x;}
        static bool readToken(string&s){s.clear();int c;do{c=getChar();}while(c!=EOF&&isspace((unsigned char)c));if(c==EOF)return false;do{s.push_back((char)c);c=getChar();}while(c!=EOF&&!isspace((unsigned char)c));if(c!=EOF)ungetChar();return true;}
    };
    static const int BASE=1e8,DIGIT=8,M=13;
    using CD=complex<double>;
    vector<long long>a;bool sign;int scale;
    bool isZero()const{return (a.size()==1&&a[0]==0)||a.empty();}
    void trim(){while(a.size()>1&&a.back()==0)a.pop_back();if(a.empty())a.push_back(0),sign=0;if(isZero())sign=0,scale=0;}
    Fixed shift(int k)const{Fixed r=*this;r.scale+=k;r.trim();return r;}
    Fixed shift_a(int k)const{
        if(k==0||isZero())return *this;
        Fixed r;r.scale=scale,r.sign=sign;
        if(k>0){r.a.assign(a.size()+k,0);for(int i=0;i<(int)a.size();i++)r.a[i+k]=a[i];return r;}
        k=-k;if(k>=(int)a.size())return Fixed(0);r.a.assign(a.begin()+k,a.end());return r;
    }
    Fixed align(int t)const{if(scale==t)return *this;int d=t-scale;Fixed r=shift_a(-d);r.scale=t;return r;}
    int compAbs(const Fixed&b)const{
        int m=min(scale,b.scale);Fixed A=align(m),B=b.align(m);
        if(A.a.size()!=B.a.size())return A.a.size()>B.a.size()?1:-1;
        for(int i=(int)A.a.size()-1;i>=0;--i)if(A.a[i]!=B.a[i])return A.a[i]>B.a[i]?1:-1;
        return 0;
    }
    bool isSmall()const{
        if((int)a.size()+scale>2||scale<0)return false;
        long long v=0;for(int i=(int)a.size()-1;i>=0;--i)v=v*BASE+a[i];
        v*=powl(BASE,scale);return v<=1000000000ll;
    }
    Fixed absAdd(const Fixed&b)const{
        int m=min(scale,b.scale);Fixed A=align(m),B=b.align(m),r;
        r.a.clear(),r.scale=A.scale;int n=max((int)A.a.size(),(int)B.a.size()),c=0;
        for(int i=0;i<n||c;++i){int s=c;if(i<(int)A.a.size())s+=A.a[i];if(i<(int)B.a.size())s+=B.a[i];r.a.push_back(s%BASE);c=s/BASE;}
        r.trim();return r;
    }
    Fixed absSub(const Fixed&b)const{
        int m=min(scale,b.scale);Fixed A=align(m),B=b.align(m),r;
        r.a.clear(),r.scale=A.scale;int n=A.a.size(),br=0;
        for(int i=0;i<n;++i){int d=A.a[i]-br;if(i<(int)B.a.size())d-=B.a[i];if(d<0)d+=BASE,br=1;else br=0;r.a.push_back(d);}
        r.trim();return r;
    }
    static void change(vector<CD>&a,int n){
        static vector<int>rev;static int ln=-1;
        if(ln!=n){rev.resize(n);rev[0]=0;for(int i=1;i<n;++i)rev[i]=(rev[i>>1]>>1)+(i&1)*(n>>1);ln=n;}
        for(int i=0;i<n;++i)if(i<rev[i])swap(a[i],a[rev[i]]);
    }
    static void FFT(vector<CD>&a,int n,int f){
        change(a,n);static vector<CD>wt;static int mx=0;
        if(mx<n){mx=1;while(mx<n)mx<<=1;wt.resize(mx/2);for(int i=0;i<mx/2;++i)wt[i]=CD(cos(2*PI*i/mx),sin(2*PI*i/mx));}
        for(int h=2;h<=n;h<<=1){int st=mx/h;
            for(int i=0;i<n;i+=h)for(int j=0;j<h/2;++j){CD w=wt[j*st];if(f==-1)w=conj(w);CD u=a[i+j],v=w*a[i+j+h/2];a[i+j]=u+v;a[i+j+h/2]=u-v;}
        }
        if(f==-1)for(int i=0;i<n;++i)a[i]/=n;
    }
    Fixed FFTMultiSingle(const Fixed&b)const{
        int n=a.size(),m=b.a.size(),len=n+m,sz=1;while(sz<len)sz<<=1;
        vector<CD>P(sz),Q(sz),X(sz),Y(sz);
        for(int i=0;i<n;i++){int a0=a[i]&((1<<M)-1),a1=a[i]>>M;P[i]=CD(a0,a1);}
        for(int i=0;i<m;i++){int b0=b.a[i]&((1<<M)-1),b1=b.a[i]>>M;Q[i]=CD(b0,b1);}
        FFT(P,sz,1),FFT(Q,sz,1);
        for(int k=0;k<sz;k++){
            int rv=(sz-k)&(sz-1);CD cjP=conj(P[rv]),A0=(P[k]+cjP)*0.5,A1=(P[k]-cjP)*CD(0,-0.5);
            CD cjQ=conj(Q[rv]),B0=(Q[k]+cjQ)*0.5,B1=(Q[k]-cjQ)*CD(0,-0.5);
            CD C0=A0*B0,C1=A0*B1,C2=A1*B0,C3=A1*B1;X[k]=C0+CD(0,1)*C1;Y[k]=C2+CD(0,1)*C3;
        }
        FFT(X,sz,-1),FFT(Y,sz,-1);
        Fixed r;r.a.clear();r.a.resize(n+m);r.scale=scale+b.scale;long long c=0;
        for(int i=0;i<n+m;i++){
            __int128 c0=llround(X[i].real()),c1=llround(X[i].imag()),c2=llround(Y[i].real()),c3=llround(Y[i].imag());
            __int128 v=c0+((c1+c2)<<M)+(c3<<(M<<1))+c;r.a[i]=v%BASE;c=v/BASE;
        }
        while(c){r.a.push_back(c%BASE);c/=BASE;}
        r.trim();return r;
    }
    Fixed FFTMulti(const Fixed&b)const{
        int n=a.size(),m=b.a.size();const int SEG=2000000;
        if(min(n,m)<=SEG)return FFTMultiSingle(b);
        Fixed r;r.a.assign(n+m+4,0);r.scale=scale+b.scale;r.sign=false;
        for(int i=0;i<n;i+=SEG){
            int na=min(SEG,n-i);Fixed sa;sa.a.assign(a.begin()+i,a.begin()+i+na);sa.scale=scale+i;sa.sign=false;
            Fixed p=sa.FFTMultiSingle(b);int pl=p.a.size();
            if(i+pl>(int)r.a.size())r.a.resize(i+pl+4,0);
            for(int k=0;k<pl;++k){
                long long v=r.a[i+k]+p.a[k];r.a[i+k]=v%BASE;
                if(v>=BASE){int pos=i+k+1;if(pos>=(int)r.a.size())r.a.push_back(0);r.a[pos]+=v/BASE;
                    while(r.a[pos]>=BASE){r.a[pos]-=BASE;++pos;if(pos>=(int)r.a.size())r.a.push_back(0);r.a[pos]+=1;}}
            }
        }
        r.trim();return r;
    }
    Fixed NaiveMulti(const Fixed&b)const{
        int n=a.size(),m=b.a.size();Fixed r;r.a.assign(n+m+2,0),r.scale=scale+b.scale;
        for(int i=0;i<n;i++){
            long long c=0;
            for(int j=0;j<m;j++){long long cur=r.a[i+j]+a[i]*b.a[j]+c;r.a[i+j]=cur%BASE;c=cur/BASE;}
            for(int k=i+m;c>0;k++){long long cur=r.a[k]+c;r.a[k]=cur%BASE;c=cur/BASE;}
        }
        r.trim();return r;
    }
    Fixed absMulti(const Fixed&b)const{
        int n=a.size(),m=b.a.size();
        if(1ll*n*m<=1000||min(n,m)<=32)return NaiveMulti(b);
        return FFTMulti(b);
    }
    static Fixed reciprocal(const Fixed&B,int need){
        if(B.isZero())throw runtime_error("Division by zero");
        if(need<1)need=1;
        Fixed Ba=B.abs(),Bi=Ba.shift(-Ba.scale);
        int m=Bi.a.size(),k0=min(need+2,8),total=m+k0;
        Fixed x;x.scale=-total;x.sign=false;x.a.assign(total,0);
        vector<long long>rem(m+2,0);int si;if(m>=2){rem[m-2]=1;si=m-2;}else{rem[0]=1;si=0;}
        auto le=[&](long long qq)->bool{
            long long c=0;bool res=true;
            for(int j=0;j<(int)rem.size();++j){
                long long v=c;if(j<m)v+=qq*Bi.a[j];
                long long blk=v%BASE;c=v/BASE;
                if(blk!=rem[j])res=(blk<rem[j]);
            }
            if(c>0)res=false;return res;
        };
        for(int i=si;i<total;++i){
            for(int j=(int)rem.size()-1;j>0;--j)rem[j]=rem[j-1];rem[0]=0;
            long double ib=1.0L/BASE,num=rem[m],den=Bi.a[m-1];
            if(m>=1)num+=(long double)rem[m-1]*ib;
            if(m>=2)num+=(long double)rem[m-2]*ib*ib;
            if(m>=2)den+=(long double)Bi.a[m-2]*ib;
            long long q=(long long)(num/den*BASE);if(q<0)q=0;if(q>=BASE)q=BASE-1;
            while(q>0&&!le(q))--q;while(q+1<BASE&&le(q+1))++q;
            x.a[total-1-i]=q;
            long long c=0;
            for(int j=0;j<m;++j){long long v=c+q*Bi.a[j];long long blk=v%BASE;c=v/BASE;rem[j]-=blk;if(rem[j]<0){rem[j]+=BASE;c++;}}
            for(int j=m;j<(int)rem.size()&&c;++j){long long blk=c%BASE;c/=BASE;rem[j]-=blk;if(rem[j]<0){rem[j]+=BASE;c++;}}
        }
        x.trim();int tk=need+2,kc=k0;Fixed two(2);
        while(kc<tk){int kn=min(2*kc,tk),nt=m+kn;Fixed t=(Bi*x).trunc(-kn);Fixed df=two.trunc(-kn)-t;x=(x*df).trunc(-nt);kc=kn;}
        if(Ba.scale!=0)x=x.shift(-Ba.scale);x.sign=false;return x;
    }
    pair<Fixed,Fixed> absDivide(const Fixed&b)const{
        Fixed A=this->abs(),B=b.abs();
        if(B.isZero())throw runtime_error("absDivide: B is zero");
        if(A<B)return {Fixed(0),A};
        int need=(int)A.a.size()-(int)B.a.size()+4;Fixed invB=reciprocal(B,need);
        if(invB.isZero()||invB.sign)throw runtime_error("absDivide: invB invalid");
        invB.trim();Fixed Q=(A*invB).trunc(0),R=A-B*Q;
        if(Q.sign)throw runtime_error("absDivide: Q negative");
        int c=0;while(R>=B){Q=Q+Fixed(1);R=R-B;if(++c>10)throw runtime_error("absDivide: R>=B loop");}
        c=0;while(R<Fixed(0)){Q=Q-Fixed(1);R=R+B;if(++c>10)throw runtime_error("absDivide: R<0 loop");}
        if(R<Fixed(0)||R>=B)throw runtime_error("absDivide: R out of [0,B)");
        Q.trim();R.trim();return {Q,R};
    }
    static void pr(const string&s){fwrite(s.data(),1,s.size(),stdout);}
public:
    Fixed():a({0}),sign(false),scale(0){}
    Fixed(long long x):sign(false),scale(0){
        if(x==0){a={0};return;}
        bool ng=x<0;unsigned long long u=ng?(unsigned long long)(-(__int128)x):(unsigned long long)x;sign=ng;
        while(u)a.push_back(u%BASE),u/=BASE;trim();
    }
    template<class T,typename enable_if<is_integral<T>::value,int>::type=0>Fixed(T x):Fixed((long long)x){}
    Fixed(float)=delete;Fixed(double)=delete;Fixed(long double)=delete;
    Fixed(const string&s):sign(false),scale(0){
        a.clear();int n=s.size(),i=0;
        if(i<n&&(s[i]=='+'||s[i]=='-')){sign=s[i]=='-';++i;}
        string dg;int fl=0;bool dot=0,hd=0;
        for(;i<n;++i){
            char c=s[i];
            if(c=='.'){if(dot)throw runtime_error("bad number: multiple decimal points");dot=1;}
            else if(c=='e'||c=='E')break;
            else if(isdigit(c)){hd=1;dg+=c;if(dot)++fl;}
            else throw runtime_error("bad number: invalid character");
        }
        long long ex=0;
        if(i<n){
            ++i;bool en=0;
            if(i<n&&(s[i]=='+'||s[i]=='-')){en=s[i]=='-';++i;}
            if(i>=n)throw runtime_error("bad exponent");
            long long e=0;bool ed=0;
            for(;i<n;++i){char c=s[i];if(!isdigit(c))throw runtime_error("bad exponent");ed=1;int d=c-'0';if(e>(LLONG_MAX-d)/10)throw runtime_error("exponent overflow");e=e*10+d;}
            if(!ed)throw runtime_error("bad exponent");ex=en?-e:e;
        }
        if(!hd){a={0};sign=0;scale=0;return;}
        int p=0;while(p+1<(int)dg.size()&&dg[p]=='0')++p;if(p)dg.erase(0,p);
        if(dg=="0"){a={0};sign=0;scale=0;return;}
        a.clear();int ln=dg.size();
        for(int r=ln;r>0;r-=8){int l=max(0,r-8),v=0;for(int j=l;j<r;++j)v=v*10+dg[j]-'0';a.push_back(v);}
        __int128 e10=(__int128)ex-fl,q128=e10/8;int r=(int)(e10%8);
        if(r<0){r+=8;--q128;}
        if(r){static const int pw[8]={1,10,100,1000,10000,100000,1000000,10000000};*this=*this*(long long)pw[r];}
        if(q128<INT_MIN||q128>INT_MAX)throw runtime_error("scale overflow");
        scale=(int)q128;trim();
    }
    static Fixed fromIntExp(long long x,int exp8){Fixed r(x);if(r.isZero())return r;r.scale=exp8;r.trim();return r;}
    static Fixed fromDouble(long double v,int sig=18){
        if(!isfinite(v))throw runtime_error("Fixed::fromDouble: not finite");
        if(sig<1)sig=1;if(sig>100)sig=100;char buf[512];snprintf(buf,sizeof(buf),"%.*Lg",sig,v);return Fixed(buf);
    }
    Fixed divide(const Fixed&b,int dp=-1)const{
        if(b.isZero())throw runtime_error("Division by zero");if(isZero())return Fixed(0);
        Fixed A=this->abs(),B=b.abs();
        if(dp<0){int dA=(int)A.a.size()*8+A.scale*8,dB=(int)B.a.size()*8+B.scale*8;int qi=max(0,dA-dB);dp=qi+32;}
        int fl=((dp+7)/8)*8,qs=-fl/8;int cm=min(A.scale,B.scale);A=A.align(cm);B=B.align(cm);
        Fixed Ai=A.shift(-cm),Bi=B.shift(-cm),As;As.a=Ai.shift_a(-qs).a;As.sign=Ai.sign;As.scale=0;As.trim();
        pair<Fixed,Fixed>dr=As.absDivide(Bi);Fixed Qv=dr.first,R=dr.second;
        if((R*Fixed(2LL))>=Bi)Qv=Qv+Fixed(1);
        Fixed Q=Qv.shift(qs);Q.sign=(sign!=b.sign)&&!Q.isZero();return Q;
    }
    pair<Fixed,Fixed> div_mod(const Fixed&b)const{
        Fixed A=this->abs(),B=b.abs();pair<Fixed,Fixed>r=A.absDivide(B);
        if(!r.first.isZero())r.first.sign=(sign!=b.sign);r.second.sign=sign&&!r.second.isZero();return r;
    }
    bool operator==(const Fixed&b)const{return sign==b.sign&&compAbs(b)==0;}
    bool operator!=(const Fixed&b)const{return !(*this==b);}
    bool operator<(const Fixed&b)const{if(sign!=b.sign)return sign==1;int c=compAbs(b);return sign?c>0:c<0;}
    bool operator>(const Fixed&b)const{return b<*this;}
    bool operator<=(const Fixed&b)const{return !(*this>b);}
    bool operator>=(const Fixed&b)const{return !(*this<b);}
    Fixed operator-()const{Fixed r=*this;if(isZero())r.sign=0;else r.sign^=1;return r;}
    Fixed operator+(const Fixed&b)const{
        if(isSmall()&&b.isSmall())return Fixed(to_ll()+b.to_ll());
        if(sign==b.sign){Fixed r=absAdd(b);r.sign=sign;return r;}
        int c=compAbs(b);Fixed r;
        if(c>=0){r=absSub(b);if(!r.isZero())r.sign=sign;}else{r=b.absSub(*this);if(!r.isZero())r.sign=b.sign;}return r;
    }
    Fixed operator-(const Fixed&b)const{return *this+(-b);}
    Fixed operator*(const long long&x)const{
        if(x==0||isZero())return Fixed(0);
        Fixed r;r.sign=sign^(x<0);r.a.clear(),r.scale=scale;__int128 abx=x<0?-x:x,c=0;
        for(int i=0;i<(int)a.size()||c;++i){if(i<(int)a.size())c+=(__int128)a[i]*abx;r.a.push_back(c%BASE);c/=BASE;}
        r.trim();return r;
    }
    Fixed operator*(const Fixed&b)const{if(isZero()||b.isZero())return Fixed(0);Fixed r=absMulti(b);r.sign=sign^b.sign;return r;}
    Fixed operator/(long long x)const{
        if(x==0)throw runtime_error("Fixed divided by 0");if(isZero())return Fixed(0);
        Fixed r;r.sign=sign^(x<0);x=x>0?x:-x;r.scale=scale;r.a.resize(a.size());long long rem=0;
        for(int i=(int)a.size()-1;i>=0;--i){__int128 cur=(__int128)rem*BASE+a[i];r.a[i]=cur/x;rem=cur%x;}
        r.trim();return r;
    }
    Fixed operator/(const Fixed&b)const{if(b.isZero())throw runtime_error("Fixed divided by 0");if(isZero())return Fixed(0);return divide(b);}
    Fixed operator%(const Fixed&b)const{if(b.isZero())throw runtime_error("Fixed modulo by 0");return div_mod(b).second;}
    Fixed& operator+=(const Fixed&b){*this=*this+b;return *this;}
    Fixed& operator-=(const Fixed&b){*this=*this-b;return *this;}
    Fixed& operator*=(const long long&b){*this=*this*b;return *this;}
    Fixed& operator*=(const Fixed&b){*this=*this*b;return *this;}
    Fixed& operator/=(const long long&b){*this=*this/b;return *this;}
    Fixed& operator/=(const Fixed&b){*this=*this/b;return *this;}
    friend Fixed operator+(long long lhs, const Fixed& rhs) { return Fixed(lhs) + rhs; }
    friend Fixed operator-(long long lhs, const Fixed& rhs) { return Fixed(lhs) - rhs; }
    friend Fixed operator*(long long lhs, const Fixed& rhs) { return Fixed(lhs) * rhs; }
    Fixed qpow(long long b)const{
        if(b<0)throw runtime_error("Negative Exp");Fixed ans(1),now=*this;
        while(b){if(b&1)ans*=now;now*=now;b>>=1;}return ans;
    }
    string to_string()const{
        if(isZero())return "0";
        string s;s.reserve((a.size()+std::abs(scale)+2)*8);if(sign)s+='-';char buf[32];
        if(scale>=0){
            sprintf(buf,"%lld",a.back());s+=buf;
            for(int i=(int)a.size()-2;i>=0;--i){sprintf(buf,"%08lld",a[i]);s+=buf;}
            for(int i=0;i<scale;++i)s+="00000000";
        }else{
            int r=-scale,ib=(int)a.size()-r;
            if(ib>0){sprintf(buf,"%lld",a.back());s+=buf;for(int i=(int)a.size()-2;i>=r;--i){sprintf(buf,"%08lld",a[i]);s+=buf;}}
            else s+='0';
            int lz=-1,low=min(r,(int)a.size());for(int i=0;i<low;++i)if(a[i]!=0){lz=i;break;}
            if(lz!=-1){s+='.';for(int idx=r-1;idx>=lz;--idx){if(idx<(int)a.size()){sprintf(buf,"%08lld",a[idx]);s+=buf;}else s+="00000000";}}
        }
        return s;
    }
    string to_string(int k)const{
        if(k<0)k=0;if(isZero()){if(k==0)return "0";string s="0.";for(int i=0;i<k;++i)s+='0';return s;}
        string full=to_string();size_t dot=full.find('.');
        if(dot==string::npos){if(k==0)return full;string s=full+".";for(int i=0;i<k;++i)s+='0';return s;}
        string ip=full.substr(0,dot),fp=full.substr(dot+1);
        if((int)fp.size()<=k){if(k==0)return ip;fp+=string(k-fp.size(),'0');return ip+"."+fp;}
        int g=fp[k]-'0';fp=fp.substr(0,k);
        if(g>=5){int i=(int)fp.size()-1,c=1;while(i>=0&&c){int d=fp[i]-'0'+c;fp[i]='0'+d%10;c=d/10;--i;}
            if(c){int j=(int)ip.size()-1,cc=1;while(j>=0&&cc){if(ip[j]=='-')break;int d=ip[j]-'0'+cc;ip[j]='0'+d%10;cc=d/10;--j;}
                if(cc){if(!ip.empty()&&ip[0]=='-')ip="-1"+ip.substr(1);else ip="1"+ip;}}}
        if(fp.empty())return ip;return ip+"."+fp;
    }
    bool read(){string s;if(!FastInput::readToken(s))return false;try{*this=Fixed(s);}catch(const exception&){return false;}return true;}
    void write()const{pr(to_auto(20));}
    void write(int k)const{pr(to_auto(k));}
    void write_exact()const{pr(to_string());}
    void write_exact(int k)const{pr(to_string(k));}
    void write_scientific(int sig=20)const{pr(to_scientific(sig));}
    friend istream& operator>>(istream&is,Fixed&x){string s;if(!(is>>s))return is;try{x=Fixed(s);}catch(const exception&){is.setstate(ios::failbit);}return is;}
    friend ostream& operator<<(ostream&os,const Fixed&x){return os<<x.to_auto(20);}
    Fixed abs()const{Fixed r=*this;r.sign=0;return r;}
    Fixed trunc(int t)const{if(scale==t)return *this;int k=scale-t;Fixed r=shift_a(k);r.scale=t;r.trim();return r;}
    long long to_ll()const{long long v=0;for(int i=(int)a.size()-1;i>=0;--i)v=v*BASE+a[i];v*=powl(BASE,scale);return sign?-v:v;}
    double to_double()const{double v=0;for(int i=(int)a.size()-1;i>=0;--i)v=v*BASE+a[i];if(scale>0)for(int i=0;i<scale;++i)v*=BASE;else for(int i=0;i<-scale;++i)v/=BASE;return sign?-v:v;}
    int digit_count()const{
        if(isZero())return 0;
        for(int i=(int)a.size()-1;i>=0;--i)if(i+scale>=0&&a[i]!=0){long long t=a[i];int d=0;while(t>0){d++;t/=10;}return (i+scale)*8+d;}
        return 0;
    }
    Fixed sqrt(int prec)const{
    if(sign) throw runtime_error("sqrt of negative");
    if(isZero()) return Fixed(0);
    if(prec<0){int dg=(int)a.size()*8+std::abs(scale)*8;prec=dg/2+16;}
    if(prec<1) prec=1;
    long long e=exponent();long long ae=e>=0?e:-e;
    long long wpLL=(long long)prec+ae+(ae+1)/2+80;
    if(wpLL>INT_MAX-8) throw runtime_error("sqrt precision too large");
    int wp=(int)wpLL;int wb=(wp+7)/8;
    Fixed y;
    double xd=to_double();
    if(isfinite(xd)&&xd>1e-300&&xd<1e300){long double yd=1.0L/sqrtl((long double)xd);char buf[128];snprintf(buf,sizeof(buf),"%.40Lg",yd);y=Fixed(buf);}
    else{long long he=e/2;char buf[64];snprintf(buf,sizeof(buf),"1e%lld",-he);y=Fixed(buf);}
    Fixed onePointFive("1.5"),zeroPointFive("0.5");
    Fixed halfX =(*this)*zeroPointFive;
    const int maxIter=64;
    for(int it=0;it<maxIter;++it){
        Fixed y_old=y;
        Fixed y2=(y*y).trunc(-wb);
        Fixed t=(onePointFive-halfX*y2).trunc(-wb);
        y=(y*t).trunc(-wb);
        Fixed diff=(y-y_old).abs();
        if(diff.isZero()||diff.exponent()<-wp) break;
    }
    Fixed r=(*this)*y;
    r=r.truncToDigits(prec);
    Fixed unit("1e-"+std::to_string(prec));
    int steps = 0;
    while(r*r>*this){r-=unit;if(++steps>1000) throw runtime_error("sqrt correction failed");}
    steps=0;
    while((r+unit)*(r+unit) <= *this){r+=unit;if(++steps>1000) throw runtime_error("sqrt correction failed");}
    return r;
}

    Fixed floor()const{if(scale>=0)return *this;Fixed t=trunc(0);if(sign&&t!=*this)t=t-Fixed(1);return t;}
    Fixed ceil()const{if(scale>=0)return *this;Fixed t=trunc(0);if(!sign&&t!=*this)t=t+Fixed(1);return t;}
    Fixed round()const{if(scale>=0)return *this;return Fixed(to_string(0));}
    Fixed roundToDigits(int k)const{if(k<0)k=0;return Fixed(to_string(k));}
    Fixed truncToDigits(int k)const{
        if(k<0)k=0;string s=to_string();size_t dp=s.find('.');if(dp==string::npos)return *this;
        string ip=s.substr(0,dp),fp=s.substr(dp+1);if((int)fp.size()<=k)return *this;fp=fp.substr(0,k);
        if(k==0)return Fixed(ip);return Fixed(ip+"."+fp);
    }
    long long exponent()const{
        if(isZero())throw runtime_error("exponent of zero");
        for(int i=(int)a.size()-1;i>=0;--i)if(a[i]!=0){long long t=a[i],d=0;while(t>0){d++;t/=10;}return 8LL*((long long)i+scale)+d-1;}
        throw runtime_error("exponent of zero");
    }
    string to_scientific(int sig=20)const{
        if(isZero())return "0";if(sig<1)sig=1;int k=a.size()-1;while(k>=0&&a[k]==0)k--;if(k<0)return "0";
        long long t=a[k],dk=0;while(t>0){dk++;t/=10;}long long e=8LL*((long long)k+scale)+dk-1;
        string digits;digits.reserve(sig+16);char buf[16];snprintf(buf,sizeof(buf),"%lld",a[k]);digits+=buf;
        for(int i=k-1;i>=0&&(int)digits.size()<sig+1;--i){snprintf(buf,sizeof(buf),"%08lld",a[i]);digits+=buf;}
        if((int)digits.size()<sig+1)digits+=string(sig+1-digits.size(),'0');
        string mant=digits.substr(0,sig);
        if(digits[sig]>='5'){int i=sig-1;while(i>=0&&mant[i]=='9'){mant[i]='0';--i;}if(i>=0)mant[i]++;else{mant="1"+string(sig-1,'0');e++;}}
        string s;if(sign)s+='-';s+=mant[0];
        if(sig>1){string frac=mant.substr(1);while(!frac.empty()&&frac.back()=='0')frac.pop_back();if(!frac.empty())s+='.'+frac;}
        s+='e';s+=(e>=0?'+':'-');s+=std::to_string(e>=0?e:-e);return s;
    }
    string to_auto(int sig=20)const{if(isZero())return "0";long long e=exponent();if(e>=-100&&e<=100)return to_string(sig);return to_scientific(sig);}
};
struct BigInt{
private:
    Fixed val;
    explicit BigInt(const Fixed&f):val(f.trunc(0)){if(val!=f)throw runtime_error("BigInt: non-interger Fixed");}
public:
    BigInt():val(0){}
    BigInt(long long x):val(x){}
    BigInt(const string&s){
        if(s.empty())throw runtime_error("BigInt: empty string");size_t i=0;if(s[i]=='+'||s[i]=='-')++i;
        if(i==s.size())throw runtime_error("BigInt: bad integer");
        for(size_t j=i;j<s.size();++j)if(!isdigit((unsigned char)s[j]))throw runtime_error("BigInt: non-integer string");
        val=Fixed(s);if(val.scale!=0)throw runtime_error("BigInt: internal non-integer");
    }
    BigInt operator+(const BigInt&b)const{return BigInt(val+b.val);}
    BigInt operator-(const BigInt&b)const{return BigInt(val-b.val);}
    BigInt operator*(const BigInt&b)const{return BigInt(val*b.val);}
    BigInt operator/(const BigInt&b)const{return BigInt(val.div_mod(b.val).first);}
    BigInt operator%(const BigInt&b)const{return BigInt(val.div_mod(b.val).second);}
    BigInt& operator+=(const BigInt&b){val+=b.val;return *this;}
    BigInt& operator-=(const BigInt&b){val-=b.val;return *this;}
    BigInt& operator*=(const BigInt&b){val*=b.val;return *this;}
    BigInt& operator/=(const BigInt&b){*this=*this/b;return *this;}
    BigInt& operator%=(const BigInt&b){*this=*this%b;return *this;}
    BigInt operator/(long long x)const{return BigInt(val/x);}
    BigInt operator%(long long x)const{return BigInt(val%x);}
    BigInt& operator/=(long long x){val/=x;return *this;}
    friend BigInt operator+(long long lhs, const BigInt& rhs) { return BigInt(lhs) + rhs; }
    friend BigInt operator-(long long lhs, const BigInt& rhs) { return BigInt(lhs) - rhs; }
    friend BigInt operator*(long long lhs, const BigInt& rhs) { return BigInt(lhs) * rhs; }
    bool operator==(const BigInt&b)const{return val==b.val;}
    bool operator!=(const BigInt&b)const{return val!=b.val;}
    bool operator<(const BigInt&b)const{return val<b.val;}
    bool operator>(const BigInt&b)const{return val>b.val;}
    bool operator<=(const BigInt&b)const{return val<=b.val;}
    bool operator>=(const BigInt&b)const{return val>=b.val;}
    BigInt operator-()const{return BigInt(-val);}
    BigInt abs()const{return BigInt(val.abs());}
    BigInt qpow(long long e)const{return BigInt(val.qpow(e));}
    string to_string()const{return val.to_string();}
    long long to_ll()const{return val.to_ll();}
    bool read(){string s;if(!Fixed::FastInput::readToken(s))return false;try{*this=BigInt(s);}catch(const exception&){return false;}return true;}
    void write()const{val.write_exact();}
    friend istream& operator>>(istream&is,BigInt&x){string s;if(!(is>>s))return is;try{x=BigInt(s);}catch(const exception&){is.setstate(ios::failbit);}return is;}
    friend ostream& operator<<(ostream&os,const BigInt&x){return os<<x.to_string();}
    BigInt sqrt()const{
        Fixed Z(0);if(val<Z)throw runtime_error("sqrt of negative");if(val==Z)return BigInt(0);
        BigInt g(1);int d=val.digit_count(),hd=d/2+1;for(int i=0;i<hd;++i)g=g*BigInt(10);
        while(true){BigInt ng=(g+*this/g)/2LL;if(ng>=g)break;g=ng;}return g;
    }
    string toBinary()const{
        Fixed Z(0);if(val==Z)return "0";bool neg=(val<Z);BigInt x(val.abs()),two(2);string r;
        while(x.val!=Z){BigInt q=x/two,e=x-q*two;r+=char('0'+(int)e.to_ll());x=q;}
        reverse(r.begin(),r.end());if(neg)r="-"+r;return r;
    }
    string toHex(bool up=true)const{
        Fixed Z(0);if(val==Z)return "0";bool neg=(val<Z);BigInt x(val.abs()),s6(16);string r;
        while(x.val!=Z){BigInt q=x/s6,e=x-q*s6;int d=(int)e.to_ll();r+=(d<10)?char('0'+d):char((up?'A':'a')+d-10);x=q;}
        reverse(r.begin(),r.end());if(neg)r="-"+r;return r;
    }
    static BigInt fromBinary(const string&s){
        BigInt r(0),two(2);bool neg=false;size_t i=0;if(i<s.size()&&(s[i]=='-'||s[i]=='+')){neg=(s[i]=='-');i++;}
        for(;i<s.size();i++)r=r*two+BigInt(s[i]-'0');return neg?-r:r;
    }
    static BigInt fromHex(const string&s){
        BigInt r(0),s6(16);bool neg=false;size_t i=0;if(i<s.size()&&(s[i]=='-'||s[i]=='+')){neg=(s[i]=='-');i++;}
        for(;i<s.size();i++){int v;char c=s[i];if(c>='0'&&c<='9')v=c-'0';else if(c>='a'&&c<='f')v=c-'a'+10;else if(c>='A'&&c<='F')v=c-'A'+10;else continue;r=r*s6+BigInt(v);}
        return neg?-r:r;
    }
};
namespace pi_calc {

Fixed pow10_fixed(int e) {
    if (e <= 0) return Fixed(1);
    return Fixed(string("1e") + to_string(e));
}

// Chudnovsky 二分拆分
// P/Q/T 始终保持 scale = 0,即整数
void chud_bs(int a, int b, Fixed& P, Fixed& Q, Fixed& T) {
    if (b - a == 1) {
    long long aa = a;
        if (a == 0) {
            P = Fixed(1);
            Q = Fixed(1);
        } else {


            // P = (6a-5)(2a-1)(6a-1)
            P = Fixed(6 * aa - 5)
              * Fixed(2 * aa - 1)
              * Fixed(6 * aa - 1);

            // Q = a^3 * 640320^3 / 24
            // 640320^3 / 24 = 10939058860032000
            static const Fixed C("10939058860032000");
            Q = Fixed(aa) * Fixed(aa) * Fixed(aa) * C;
        }

        T = P * Fixed(13591409LL + 545140134LL * aa);
        if (a & 1) T = -T;
    } else {
        int m = (a + b) / 2;

        Fixed P1, Q1, T1, P2, Q2, T2;
        chud_bs(a, m, P1, Q1, T1);
        chud_bs(m, b, P2, Q2, T2);

        P = P1 * P2;
        Q = Q1 * Q2;
        T = T1 * Q2 + P1 * T2;
    }
}

// 返回 pi,prec 是小数点后的位数
string pi_chudnovsky(int prec) {
    if (prec < 0) prec = 0;

    const int guard = 30;     // 保护位
    int S = prec + guard;     // 实际计算位数

    // Chudnovsky 每项约 14.18 位
    int K = S / 14 + 3;

    Fixed P, Q, T;
    chud_bs(0, K, P, Q, T);

    // N = 10005 * 10^(2S)
    // sqrt(N) = sqrt(10005) * 10^S
    Fixed sqrt_scaled = (Fixed(10005).sqrt(S) * pow10_fixed(S)).trunc(0);

    // pi_scaled ~= pi * 10^S
    // num / T = 426880 * sqrt(10005) * Q / T * 10^S
    Fixed num = sqrt_scaled * 426880LL;
    num = num * Q;

    // 取整数商,相当于 floor(num / T),因为 num、T 都是正数
    Fixed pi_scaled = num.div_mod(T).first;

    // 去掉 guard 位,四舍五入
    Fixed scale = pow10_fixed(guard);
    Fixed half  = pow10_fixed(guard - 1) * 5LL;

    Fixed rounded = (pi_scaled + half).div_mod(scale).first;

    string s = rounded.to_string();

    // 补足长度,保证小数点位置正确
    if ((int)s.size() <= prec) {
        s = string(prec + 1 - s.size(), '0') + s;
    }

    if (prec == 0) return s;
    return s.substr(0, s.size() - prec) + "." + s.substr(s.size() - prec);
}

} // namespace pi_calc

int main() {
    freopen("pi.out", "w", stdout);

    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    if (!(cin >> n)) return 0;

    // n 表示小数点后的位数
    string pi = pi_calc::pi_chudnovsky(n);

    fwrite(pi.data(), 1, pi.size(), stdout);
    putchar('\n');

    return 0;
}
:::
测试代码:https://www.luogu.com.cn/paste/2gpa5yvo

压缩版代码(暂不可用,功能缺失):https://www.luogu.com.cn/paste/mtg626nr