您的位置:首页 > 其它

大精度整数三种运算(加法,减法,乘法)

2017-12-06 18:40 465 查看
有一些的题出的数都很大,连long long都无法存储,这时候就要用到大精度整数运算了,本质就是用数组存储每一位数,这里给出常见的三种大精度整数运算;

1.加法运算:

#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
int s[10000+10];
char s1[10000+5];
char s2[10000+5];
using namespace std;
int main()
{
int k1 = 0,k2 = 0;
scanf("%s",s1);
scanf("%s",s2);
k1 = strlen(s1);
k2 = strlen(s2);
int t = 0 ,i = 0;
int x;
while(k1>0&&k2>0)
{

x = s1[--k1]-'0'+s2[--k2]-'0'+t;
s[i++] = x%10;
t = x/10;
}
while(k1>0)
{
x = s1[--k1]-'0' + t;
s[i++] = x%10;
t = x/10;
}
while(k2>0)
{
x = s2[--k2]-'0' + t;
s[i++] = x%10;
t = x/10;
}
if(t > 0) s[i++] = 1,t=0;
i = i-1;
while(i>0&&s[i] == 0)
{
i--;
}
while(i>=0)
{
cout << s[i--];
}

return 0;
}


2.减法

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char Sa[510],Sb[510];
int a[510],b[510];
int main()
{
cin>>Sa>>Sb;
int aLen=strlen(Sa),bLen=strlen(Sb);
int l=max(aLen,bLen);
if (bLen>aLen || (aLen==bLen && !strcmp(Sa,Sb)))
{
swap(Sa,Sb);
swap(aLen,bLen);
cout<<"-";
}
for (int i=1;i<=aLen;i++) a[i]=Sa[aLen-i]-'0';
for (int i=1;i<=bLen;i++) b[i]=Sb[bLen-i]-'0';
for (int i=1;i<=l;i++)
{
a[i]=a[i]-b[i];
if (a[i]<0)
{
a[i]+=10;
a[i+1]--;
}
}
while (!a[l]) l--;
for (int i=l;i>=1;i--) cout<<a[i];
return 0;
}


3.乘法
#include <iostream>
#include <string>
using namespace std;
string a,b;
int ia[510],ib[510],pdt[1010];
int main()
{
cin>>a>>b;
/* 逆序存储 */
for(int i=0;i<a.length();i++) ia[a.length()-i-1]=a[i]-'0';
for(int i=0;i<b.length();i++) ib[b.length()-i-1]=b[i]-'0';
/*乘法的规律*/
for(int i=0;i<b.length();i++)
{
for(int j=0;j<a.length();j++)
{
pdt[i+j]+=ia[j]*ib[i];
}
}
for(int i=0;i<1009;i++)
{
if(pdt[i]>=10)
{
pdt[i+1]+=pdt[i]/10;
pdt[i]%=10;
}
}
int fact_len=0;
for(fact_len=1009;fact_len>=0;fact_len--)
{
if(pdt[fact_len]) break;
}
for(int i=fact_len;i>=0;i--)
{
cout<<pdt[i];
}
return 0;
}


相关题目:codevs3115,codevs3116,codevs3117
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: