1. 平方差
作者:
闪回
,
2024-03-25 11:11:25
,
所有人可见
,
阅读 4
高精度乘高精度
注意处理输入的负数
高精度模板背熟
#include<bits/stdc++.h>
#define int long long
using namespace std;
vector<int> A,B;
string a,b;
bool cmp(vector<int> &A,vector<int> &B)
{
if(A.size() != B.size())return A.size()>B.size();
else
{
for(int i = A.size()-1;i>=0;i--)
{
if(A[i] != B[i])return A[i] > B[i];
}
}
return true;
}
vector<int> mul(vector<int> &A,vector<int> &B)
{
vector<int> C(A.size() + B.size());
for(int i = 0;i<A.size();i++)
{
for(int j = 0;j<B.size();j++)
{
C[i+j] += A[i] * B[j];
}
}
for(int i = 0,t = 0;i<C.size();i++)
{
t += C[i];
C[i] = t % 10;
t /= 10;
}
while(C.size() > 1 && C.back() == 0)C.pop_back();
return C;
}
vector<int> sub(vector<int> &A,vector<int> &B)
{
vector<int> C;
int t = 0;
for(int i = 0;i<A.size();i++)
{
t = A[i] - t;
if(i < B.size())t -= B[i];
C.push_back((t+10) % 10);
if(t < 0)t = 1;
else t = 0;
}
while(C.size() > 1 && C.back() == 0)C.pop_back();
return C;
}
signed main()
{
string aa,bb,a,b;
cin>>aa>>bb;
if(aa[0] == '-')
for(int i = 1; i < aa.size(); i++) a += aa[i];
else a = aa;
if(bb[0] == '-')
for(int i = 1; i < bb.size(); i++) b += bb[i];
else b = bb;
for(int i = a.size()-1;i>=0;i--)A.push_back(a[i] - '0');
for(int i = b.size()-1;i>=0;i--)B.push_back(b[i] - '0');
vector<int> C = mul(A,A);
vector<int> D = mul(B,B);
vector<int> ans;
if(cmp(C,D))ans = sub(C,D);
else
{
cout<<"-";
ans = sub(D,C);
}
for(int i = ans.size()-1;i>=0;i--)cout<<ans[i];
return 0;
}