正文
增加 384 行删除 431 行
3 行未改动4567891011121314151617181920212223242526273 行未改动3132333435363738394041424344454647484950513 行未改动555657585960616263646566676869707172737475767778798081825 行未改动888990919293949596979852 行未改动15115215315415515615715832 行未改动1911921931941951961971981992002012022032042052062072082092102112122132142152162 行未改动2192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492 行未改动25225325425525625725825926022 行未改动28328428528628728828929029119 行未改动3113123133143153163173183192 行未改动3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703717 行未改动3793803813823833843853863874 行未改动39239339439539639739839940040140240340440540640728 行未改动43643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452516 行未改动5425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156163 行未改动6206216226236246256266276286296306316326333 行未改动6376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666673 行未改动6716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837844 行未改动789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910406 行未改动104710481049105010511052105310543 行未改动105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011313 行未改动> `BigInt`:高精度整数,API 更简洁。选择建议:只做整数运算用 `BigInt`;涉及小数、需要保留小数位或截断用 `Fixed`。保证数据十进制下位数 $\le 10^6$ 时精度可控。**复杂度记号**:全文用 $N$ 表示**十进制位数**,$M(N)$ 表示**两个 $N$ 位数相乘的复杂度**,按规模分三段:$$M(N)=\begin{cases}O(N^2), & N\le 500 \\O(N\log N), & 500 < N \le 8\times 10^6 \\O\!\left(\dfrac{N^2}{W}\log N\right), & N > 8\times 10^6,\text W=8\times 10^6\end{cases}$$- **第一段**($N \le 500$):朴素乘法。- **第二段**($500 < N \le 8\times 10^6$):单次 FFT。- **第三段**($N > 8\times 10^6$):分块 FFT,每 $8\times10^6$ 位一块,较少用---:::success[一、构造对象]3 行未改动| :--- | :--- | :--- | :--- || `Fixed a;` | 0 | 零 | $O(1)$ || `Fixed b(123);` | 123 | 整数 | $O(N)$ || `Fixed d("789.012");` | 789.012 | **小数用字符串** | ^|| `Fixed(1.5L, -1);` | 1.5 | 显式浮点 + 块数 | ^|```cppFixed a; // 0Fixed b(123); // 123Fixed c(-456); // -456Fixed d("789.012"); // 789.012Fixed e("-3.14"); // -3.14Fixed f(1.5L, -1); // 1.5Fixed g(1LL, 100); // 10^800```**记法**:小数用**字符串**,整数放大用 `1LL`(`Fixed(1, 100)` 编译歧义,必须写 `1LL`)。### 1.2 科学计数法```cpp3 行未改动Fixed("1E5"); // 100000(大写 E 也支持)Fixed("0e5"); // 0```指数范围 `[-100000, 100000]`,超出抛 `runtime_error`。**复杂度 $O(N)$**。### 1.3 BigInt 的构造```cppBigInt a; // 0BigInt b(123); // 123BigInt d("12345678901234567890"); // 大整数````BigInt("1.5")` 自动截断为 `1`。**复杂度 $O(N)$**。::::::success[二、四则运算]### 2.1 加减乘| 运算 | 复杂度 | $1000$ 位 | $10^5$ 位 | $10^6$ 位 || :--- | :--- | :--- | :--- | :--- || `+`、`-` | $O(N)$ | < 0.01 ms | < 1 ms | 约 10 ms || `*` | $O(M(N))$ | 0.22 ms | 40 ms | 379 ms |```cppFixed x("1.2"), y("3.4");Fixed sum = x + y; // 4.65 行未改动`M(N)` 的定义见文首。### 2.2 除法| 运算 | 复杂度 | $50000/5000$ 位 | $10^5/10^4$ 位 | $10^6/10^5$ 位 || :--- | :--- | :--- | :--- | :--- || `a / b` | $O(M(N)\log N)$ | 116 ms | 248 ms | 3443 ms |**`/` 是高精度除法**,默认保留足够位数:```cpp52 行未改动5 / Fixed("10"); // 0.510 % Fixed("3"); // Fixed("1")3 * BigInt("100"); // 300```### 2.7 复合赋值`+=`、`-=`、`*=`、`/=`、`%=` 均支持,复杂度同对应二元运算。32 行未改动```**复杂度 $O(N)$**。### 4.3 输出时控制小数位```cppFixed("2.5").write(2); // "2.50"Fixed("2.5").write(0); // "3"```**复杂度 $O(N)$**。### 4.4 五者的关系| 方法 | 作用 | 单位 | 舍入方向 || :--- | :--- | :--- | :--- || `divide(b, k)` | 计算除法并保留 `k` 位 | **位** | 四舍五入 || `trunc(k)` | 截断当前值到 `k` 块 | **块**(8 位) | 直接截断 || `roundToDigits(k)` | 舍入到 `k` 位 | **位** | 四舍五入 || `truncToDigits(k)` | 截断到 `k` 位 | **位** | 直接截断 || `write(k)` | 输出时保留 `k` 位 | **位** | 四舍五入 |::::::success[五、数学函数]### 5.1 快速幂:`qpow(b)`2 行未改动Fixed("2").qpow(10); // 1024BigInt("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^2 N)$**。| 精度 | 时间 || :--- | :--- || 100 位 | 0.14 ms || 1000 位 | 44 ms || 10000 位 | 1348 ms || 20000 位 | 3313 ms |```cppFixed("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)$**。2 行未改动BigInt("100").sqrt(); // 10BigInt("10").sqrt(); // 3(向下取整)```**实测**:4000 位输入 134 ms。### 5.5 取整| 函数 | 语义 | `-2.5` | `2.5` | 复杂度 |22 行未改动Fixed("123.456").digit_count();// 3```### 6.4 真实指数:`exponent()`返回数的真实 10 的幂次($x = m × 10^e,m \in [1, 10)$),返回 `long long`,`scale` 大时也不会溢出。**复杂度 $O(N)$**。```cppFixed("1e10").exponent(); // 10Fixed("20959.155").exponent(); // 419 行未改动```cppFixed a, b;cin >> a >> b; // 等价于 read()cout << (a / b) << '\n'; // 完整表示(等价 write_exact())````BigInt` 同理。2 行未改动**`Fixed` 的 `write` 有 5 个重载,分别对应 auto / exact / scientific:**| 调用 | 模式 | 说明 || :--- | :--- | :--- || `write()` | auto | 默认 20 位有效数字,小范围精确、大范围科学计数法 || `write(k)` | auto | `k` 位有效数字的 auto || `write_exact()` | exact | 完整精确表示,不去尾零 || `write_exact(k)` | exact | 精确到 `k` 位小数 || `write_scientific(sig)` | scientific | 科学计数法,`sig` 位有效数字,默认 20 |**auto 的切换规则**:总位数 $\le 1000$($(\text{a.size()} + |\text{scale}|) \times 8 ≤ 1000$)时完整输出 `to_string()`,否则科学计数法。```cppFixed a("1.01");a.qpow(1000);a.write(); // "20959.1555637813660064"(auto,总位数 5,精确)a.write(10); // "20959.1555637813660064"(auto,10 位有效数字,仍精确)a.write_scientific(10); // "2.095915564e+4"(科学计数法,10 位有效数字)Fixed b("0.5");b.qpow(1000); // 2^-1000 ≈ 9.33e-302b.write(); // "9.3326361850321887899e-302"(auto,总位数 1000+,科学计数法)b.write_exact(); // "0.000...9332..."(完整 1000 位小数,约 1003 字符)b.write_exact(100); // "0.000...9332..."(前 301 个 0 + 100 位有效,约 403 字符)Fixed c(1LL, 100000); // 10^800000c.write(); // "1e+800000"(auto,总位数 80 万,科学计数法)c.write_scientific(10); // "1e+800000"// c.write_exact(); // 会试图输出 80 万字符,慎用```:::warning[**`write(k)` 与 `write_exact(k)` 的区别**:]{open}`write(k)` 是 `k` 位有效数字,`write_exact(k)` 是 `k` 位小数。对 `123.456`:- `write(4)` → `123.5`(4 位有效数字)- `write_exact(4)` → `123.4560`(4 位小数):::**`BigInt` 只有 `write()`(完整整数),不支持科学计数法**——整数的每一位都是有效信息,科学计数法会丢失数据。### 8.3 `read()````cppFixed x;x.read(); // 从 stdin 读,跳过非数字非 '-/+'和非 'e/E',支持科学计数法````BigInt::read()` 同理,但不支持科学计数法,只读整数部分。### 8.4 `to_string()` / `to_scientific()`与 `write` 对应的字符串版本:7 行未改动```cppstring 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); // "20959.15556"```:::::::info[九、测试场景]4 行未改动for (int i = 1; i <= 1000; ++i) fact *= BigInt(i);fact.write();```**复杂度 $O(n \cdot M(N))$**。1000! = 2568 位约 4 ms。### 9.2 用 Machin 公式算 π| 精度 | 时间 || :--- | :--- || 100 位 | 2.4 ms || 1000 位 | 3512 ms |```cppFixed pi_machin(int need){int wn = need + 16, wnb = (wn + 7) / 8;28 行未改动- `write(k)` / `to_string(k)`:固定 `k` 位小数,**保留尾零**。- 负零不输出 `-0.00`,统一输出 `0.00`。::::::error[十一、已知限制与常见错误]| 限制 | 对策 || :--- | :--- || `Fixed(1.5)` 截断为 1 | 用 `Fixed("1.5")` || `Fixed(1, 100)` 编译歧义 | 写 `Fixed(1LL, 100)` || `trunc(k)` 单位是块 | 用 `divide(b, k)` 或 `roundToDigits` || `write(80)` 后面补零 | 用 `divide(b, 80)` || `LLONG_MIN` 做除数 UB | 极少触发 || ARM 平台 `10^6` 位精度不足 | 减小规模或换 NTT || `static` 缓存非线程安全 | 单线程使用安全 || `to_ll()` 溢出 | 调用方保证值域 || `to_double()` 溢出 | 用 `to_string` |**错误写法对照**:```cpp// ❌Fixed a(1.5); // 截断为 1Fixed b(1, 100); // 编译歧义d.write(80); // 后 56 位补零x.trunc(8); // 64 位小数,不是 8 位// ✅Fixed a("1.5");Fixed b(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.25 ms | $O(N\log N)$ || $10^4$ | ^| 4.4 ms |^ || $10^5$ | ^| 40 ms |^ || $2×10^5$ | ^ | 85 ms |^|| $5×10^5$ | ^ | 181 ms | ^ || $10^6$ | ^ | 379 ms | ^ |### 12.2 除法| 规模 | 时间 || :--- | :--- || $50000/5000$ | 116 ms || $10^5/10^4$| 248 ms || $10^6/10^5$ | 3443 ms |### 12.3 开方| 规模 | 时间 || :--- | :--- || `sqrt` 100 位 | 0.15 ms || `sqrt` 1000 位 | 44 ms || `sqrt` 10000 位 | 1348 ms || `sqrt` 20000 位 | 3313 ms || `BigInt::sqrt` 4000 位输入 | 134 ms |### 12.4 其他| 操作 | 时间 || :--- | :--- || 2000! (5736 位) | 3.7 ms || π 100 位 | 2.4 ms || π 1000 位 | 3512 ms |::::::success[十三、快速索引]{open}| 需求 | 调用 | 复杂度 || :--- | :--- | :--- || 构造小数 | `Fixed("1.5")` | $O(N)$ || 构造放大整数 | `Fixed(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` | ^ |16 行未改动:::---:::info[Code]共 579 行,约 26.4k。```cpp#include<bits/stdc++.h>using namespace std;const long double PI=acos(-1.0);struct Fixed{static const int BASE=1e8,DIGIT=8,M=15;using CD=complex<long 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<a.size();i++)r.a[i+k]=a[i];return r;}k=-k;if(k>=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=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(a.size()+scale>2||scale<0)return false;long long v=0;for(int i=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);Fixed r;r.a.clear(),r.scale=A.scale;int n=max(A.a.size(),B.a.size()),c=0;for(int i=0;i<n||c;++i){int s=c;if(i<A.a.size())s+=A.a[i];if(i<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);Fixed 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<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.5L,A1=(P[k]-cjP)*CD(0,-0.5L);CD cjQ=conj(Q[rv]),B0=(Q[k]+cjQ)*0.5L,B1=(Q[k]-cjQ)*CD(0,-0.5L);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++){3 行未改动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=1000000;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;3 行未改动}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<=5000)return NaiveMulti(b);if(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];3 行未改动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;long double 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 xs=x.align(-nt);Fixed t=(Bi*xs).trunc(-nt);Fixed df=two.align(-nt)-t;x=(xs*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()+2;Fixed invB=reciprocal(B,need);if(invB.isZero()||invB.sign)throw runtime_error("absDivide: invB invalid");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 string normalizeSci(const string&s){size_t ep=s.find_first_of("eE");if(ep==string::npos)return s;string mant=s.substr(0,ep);bool neg=false;if(!mant.empty()&&mant[0]=='-'){neg=true;mant=mant.substr(1);}long long ex;try{ex=stoll(s.substr(ep+1));}catch(...){throw runtime_error("bad exponent");}if(ex<-1000000||ex>1000000)throw runtime_error("exponent too large");string ip="0",fp="";size_t dot=mant.find('.');if(dot==string::npos)ip=mant;else{ip=mant.substr(0,dot);fp=mant.substr(dot+1);}string dg=ip+fp;int fn=0;while(fn<(int)dg.size()-1&&dg[fn]=='0')fn++;dg=dg.substr(fn);long long pp=(long long)ip.size()-fn+ex;string res;if(pp<=0)res="0."+string(-pp,'0')+dg;else if(pp>=(long long)dg.size())res=dg+string(pp-(long long)dg.size(),'0');else res=dg.substr(0,pp)+"."+dg.substr(pp);if(neg)res="-"+res;return res;}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,int sc=0):scale(sc){sign=false;if(x==0){a={0};}else{if(x<0)sign=true,x=-x;while(x>0)a.push_back(x%BASE),x/=BASE;}trim();}Fixed(long double v,int sc):scale(sc){sign=(v<0);v=fabsl(v);long double mul=powl(BASE,-sc),tmp=v*mul;unsigned long long r=llroundl(tmp);if(r==0){a={0};sign=0;return;}a.clear();while(r>0)a.push_back(r%BASE),r/=BASE;trim();}Fixed(const string&s):scale(0){sign=false;string str=normalizeSci(s);if(str.empty()){a={0};return;}if(str[0]=='-')sign=true,str.erase(0,1);size_t dp=str.find('.');if(dp!=string::npos){string ip=str.substr(0,dp),fp=str.substr(dp+1);int d=fp.size();if(d>0){int need=(8-d%8)%8;fp+=string(need,'0');scale=-((d+need)/8);}else scale=0;str=ip+fp;}while(str.size()>1&&str[0]=='0')str.erase(0,1);if(str.empty())str="0";a.clear();int ln=str.length();for(int i=ln;i>0;i-=DIGIT){int st=max(0,i-DIGIT);a.push_back(stoi(str.substr(st,i-st)));}trim();}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);Fixed 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;}4 行未改动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<a.size()||c;++i){if(i<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=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;}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;}void read(){string s;int c=getchar();while(c!=EOF&&!isdigit(c)&&c!='-')c=getchar();if(c==EOF){*this=Fixed(0);return;}if(c=='-')s+=c,c=getchar();while(isdigit(c)||c=='.')s+=c,c=getchar();if(c=='e'||c=='E'){s+=c,c=getchar();if(c=='+'||c=='-')s+=c,c=getchar();while(isdigit(c))s+=c,c=getchar();}if(s.empty()||s=="-"||s=="+"||s=="e"||s=="E"||s=="-e"||s=="-E"||s=="+e"||s=="+E")s="0";*this=Fixed(s);}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;is>>s;x=Fixed(s);return is;}friend ostream& operator<<(ostream&os,const Fixed&x){return os<<x.to_string();}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=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=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(),ae=e>=0?e:-e;int wp=prec+(int)ae+40,wb=(wp+7)/8;Fixed y;double xd=to_double();if(std::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"),halfX=(*this)*zeroPointFive;const int maxIter=64;for(int it=0;it<maxIter;++it){Fixed y_old=y,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));while(r*r>*this)r=r-unit;while((r+unit)*(r+unit)<=*this)r=r+unit;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=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{Fixed val;BigInt(const Fixed&f):val(f){}public:BigInt():val(0){}BigInt(long long x):val(x){}BigInt(const string&s){string str=s;size_t dp=str.find('.');if(dp!=string::npos)str=str.substr(0,dp);bool neg=false;if(!str.empty()&&str[0]=='-'){neg=true;str.erase(0,1);}while(str.size()>1&&str[0]=='0')str.erase(0,1);if(str.empty())str="0";val=Fixed(str);if(neg)val=-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*b.val);}6 行未改动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;}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;}3 行未改动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();}void read(){string s;int c=getchar();while(c!=EOF&&!isdigit(c)&&c!='-')c=getchar();if(c==EOF){*this=BigInt(0);return;}if(c=='-')s+=c,c=getchar();while(isdigit(c))s+=c,c=getchar();if(s.empty()||s=="-")s="0";*this=BigInt(s);}void write()const{val.write();}friend istream& operator>>(istream&is,BigInt&x){string s;is>>s;x=BigInt(s);return is;}friend ostream& operator<<(ostream&os,const BigInt&x){return os<<x.val;}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;}};int main(){return 0;}:::测试代码:https://www.luogu.com.cn/paste/2gpa5yvo压缩版代码:https://www.luogu.com.cn/paste/mtg626nr3 行未改动4567891011121314151617181920212223242526273 行未改动31323334353637383940414243444546474849505152533 行未改动575859606162636465666768697071727374757677787980818283845 行未改动9091929394959697989910052 行未改动15315415515615715815916016132 行未改动1941951961971981992002012022032042052062072082092 行未改动2122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432 行未改动24624724824925025125225325422 行未改动27727827928028128228328428519 行未改动3053063073083093103113123132 行未改动3163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603617 行未改动3693703713723733743753763774 行未改动38238338438538638738838939039139239339439539639728 行未改动42642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651716 行未改动5345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146153 行未改动6196206216226236246256266276286296306313 行未改动6356366376386396406416426436446456466476486496506516526536546556566576586596606616623 行未改动6666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597604 行未改动7657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219226 行未改动9299309319329339349359369379389393 行未改动94394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310843 行未改动> `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}$$- **第一段**($N \le 500$):朴素乘法。- **第二段**($500 < N \le 8\times 10^6$):单次 FFT。- **第三段**($N > 1.6\times 10^7$):分块 FFT,每 $1.6\times10^7$ 位一块,较少用---:::success[一、构造对象]3 行未改动| :--- | :--- | :--- | :--- || `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 块|^|```cppFixed a; // 0Fixed b(123); // 123Fixed c(-456); // -456Fixed d("789.012"); // 789.012Fixed e("-3.14"); // -3.14Fixed f = Fixed::fromDouble(1.5L); // 1.5Fixed g = Fixed::fromIntExp(1LL, 100); // 10^800```**记法**:小数用**字符串**;浮点构造已 delete,需用 Fixed::fromDouble;放大整数用 Fixed::fromIntExp。### 1.2 科学计数法```cpp3 行未改动Fixed("1E5"); // 100000(大写 E 也支持)Fixed("0e5"); // 0```指数范围过大抛 `runtime_error`。**复杂度 $O(N)$**。### 1.3 BigInt 的构造```cppBigInt a; // 0BigInt b(123); // 123BigInt 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|```cppFixed x("1.2"), y("3.4");Fixed sum = x + y; // 4.65 行未改动`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|**`/` 是高精度除法**,默认保留足够位数:```cpp52 行未改动5 / Fixed("10"); // 0.510 % Fixed("3"); // Fixed("1")3 * BigInt("100"); // 300```修改后暂不支持,可暂时显式构造来替代。### 2.7 复合赋值`+=`、`-=`、`*=`、`/=`、`%=` 均支持,复杂度同对应二元运算。32 行未改动```**复杂度 $O(N)$**。### 4.3 四者的关系| 方法 | 作用 | 单位 | 舍入方向 || :--- | :--- | :--- | :--- || `divide(b, k)` | 计算除法并保留 `k` 位 | **位** | 四舍五入 || `trunc(k)` | 截断当前值到 `k` 块 | **块**(8 位) | 直接截断 || `roundToDigits(k)` | 舍入到 `k` 位 | **位** | 四舍五入 || `truncToDigits(k)` | 截断到 `k` 位 | **位** | 直接截断 |::::::success[五、数学函数]### 5.1 快速幂:`qpow(b)`2 行未改动Fixed("2").qpow(10); // 1024BigInt("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|```cppFixed("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)$**。2 行未改动BigInt("100").sqrt(); // 10BigInt("10").sqrt(); // 3(向下取整)```**实测**:4000 位输入 10.7 ms。### 5.5 取整| 函数 | 语义 | `-2.5` | `2.5` | 复杂度 |22 行未改动Fixed("123.456").digit_count();// 3```### 6.4 真实指数:`exponent()`返回数的真实 10 的幂次($x = m × 10^e,m \in [1, 10)$),返回 `long long`。**复杂度 $O(N)$**。```cppFixed("1e10").exponent(); // 10Fixed("20959.155").exponent(); // 419 行未改动```cppFixed a, b;cin >> a >> b; // 等价于 read()cout << (a / b) << '\n'; // 等价 write() / write_auto(20)````BigInt` 同理。2 行未改动**`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 |```cppFixed 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-302b.write(); // 科学计数法b.write_exact(100); // 精确到 100 位小数Fixed c = Fixed::fromIntExp(1LL, 100000); // 10^800000c.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()````cppFixed x;x.read(); // 从 stdin 读一个空白分隔 token,再按 Fixed 字符串规则解析````BigInt::read()` 同理,但只接受整数字符串;解析失败返回 false。### 8.4 `to_string()` / `to_scientific()`与 `write` 对应的字符串版本:7 行未改动```cppstring 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[九、测试场景]4 行未改动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 |```cppFixed pi_machin(int need){int wn = need + 16, wnb = (wn + 7) / 8;28 行未改动- `write(k)` / `to_string(k)`:固定 `k` 位小数,**保留尾零**。- 负零不输出 `-0.00`,统一输出 `0.00`。::::::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` |**错误写法对照**:```cpp// ❌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` | ^ |16 行未改动:::---:::info[Code]共 430 行,约 25.8k。附带计算 $\pi$ 代码。```cpp#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++){3 行未改动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;3 行未改动}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];3 行未改动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;}4 行未改动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);}6 行未改动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;}3 行未改动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 = 10939058860032000static 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^SFixed sqrt_scaled = (Fixed(10005).sqrt(S) * pow10_fixed(S)).trunc(0);// pi_scaled ~= pi * 10^S// num / T = 426880 * sqrt(10005) * Q / T * 10^SFixed 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_calcint 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