3123. 高精度乘法II

题目链接

3123. 高精度乘法II

给定两个正整数 AB,请你计算 A×B 的值。

输入格式

共两行,第一行包含整数 A,第二行包含整数 B

输出格式

共一行,包含 A×B 的值。

数据范围

1AB105

输入样例:

2 3

输出样例:

6

解题思路

fft

A 由低位到高位的值分别为 a0,a1,,an1,构造一个 n1 次多项式 f(x)=a0+a1x+a2x2++an1xn1,同理由 B 构造的多项式 g(x)=b0+b1x+b2x2++bm1xm1,而 A=f(10),B=g(10),要求 A×B=f(10)×g(10),而 fft 可求得 h(x)=f(x)×g(x),最后即求 h(10)。注意求解的 h(x) 的系数并不是最后的答案,其系数也可能不是一位数

  • 时间复杂度:O(nlogn)

代码

// Problem: 高精度乘法II // Contest: AcWing // URL: https://www.acwing.com/problem/content/3126/ // Memory Limit: 64 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } const int N=3e5+5; const double pi=acos(-1); int n,m,bit,tot,rev[N],res[N]; char A[N],B[N]; struct cp { double x,y; cp operator+(const cp &o)const { return {x+o.x,y+o.y}; } cp operator-(const cp &o)const { return {x-o.x,y-o.y}; } cp operator*(const cp &o)const { return {x*o.x-y*o.y,x*o.y+y*o.x}; } }a[N],b[N]; void fft(cp a[],int inv) { for(int i=0;i<tot;i++) if(i<rev[i])swap(a[i],a[rev[i]]); for(int mid=1;mid<tot;mid<<=1) { cp w1={cos(pi/mid),inv*sin(pi/mid)}; for(int i=0;i<tot;i+=mid<<1) { cp wk={1,0}; for(int j=0;j<mid;j++,wk=wk*w1) { cp x=a[i+j],y=a[i+j+mid]; a[i+j]=x+wk*y,a[i+j+mid]=x-wk*y; } } } } int main() { help; cin>>A>>B; n=strlen(A),m=strlen(B); n--,m--; for(int i=0;i<=n;i++)a[i].x=A[n-i]-'0'; for(int i=0;i<=m;i++)b[i].x=B[m-i]-'0'; while((1<<bit)<n+m+1)bit++; tot=1<<bit; for(int i=0;i<tot;i++)rev[i]=rev[i>>1]>>1|((i&1)<<(bit-1)); fft(a,1),fft(b,1); for(int i=0;i<tot;i++)a[i]=a[i]*b[i]; fft(a,-1); int t=0,k=0; for(int i=0;i<tot||t;i++) { t+=a[i].x/tot+0.5; res[k++]=t%10; t/=10; } while(k>1&&!res[k-1])k--; for(int i=k-1;~i;i--)cout<<res[i]; return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/16508328.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示