您的位置:首页 > 其它

大数之乘法加法除法

2018-03-28 14:47 141 查看
加法(不成熟的小代码orz)
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
string a, b;
int res[500] = {0};
cin >> a >> b;
if(a.length() > b.length())
{
string strb(a.length()-b.length(), '0');
b = strb + b;
}
else
{
string stra(b.length()-a.length(), '0');
a = stra + a;
}
// cout << a << " " << b << endl;
for(int i = max(b.length(), a.length()) - 1; i > 0; i--)
{
res[i] += ((a[i]-'0')+(b[i]-'0'))%10;
// cout << ((a[i]-'0')+(b[i]-'0'))%10 << " ";
// cout << res[i] << endl;
res[i-1] = ((a[i]-'0')+(b[i]-'0'))/10;
}
res[0] += ((a[0]-'0')+(b[0]-'0'))%10;
// cout << res[0] << endl;
if(((a[0]-'0')+(b[0]-'0'))/10 > 0)
cout << ((a[0]-'0')+(b[0]-'0'))/10;
for(int i = 0; i < max(b.length(), a.length()); i++)
cout << res[i];
}乘法来源(蓝桥杯 矩阵翻硬币):点击打开链接

另外学到一点:一个数有奇数个约数 -> 完全平方数,因为每个数为两个(即一对)数相乘得到,完全平方数的两个数为同一个,所以为奇数个。#include <iostream>
using namespace std;
int main()
{
string a, b, num = "";
int res[10010] = {0};
int i;
cin >> a >> b;
int lena = a.length();
int lenb = b.length();
for(i = 0; i < lena; i++)
{
for(int j = 0; j < lenb; j++)
{
res[lena-1+lenb-1-i-j] += (a[i]-'0')*(b[j]-'0');
}
}
for(i = 0; i < lena+lenb; i++)
{
res[i+1] += res[i]/10;
res[i] %= 10;
}
for(i = lena+lenb; i >= 0; i--)
{
if(res[i]!=0)
break;
}
for( ; i >= 0; i--)
{
num += (char)(res[i]+'0');
}
cout << num << endl;
}除法#include <iostream>
using namespace std;
int main()
{
string a;
int b, flag = 0;
cin >> a >> b;
int temp = 0;
for(int i = 0; i < a.length(); i++)
{
temp = a[i]-'0' + temp*10;
// cout << temp << " ";
if(temp >= b)
{
cout << temp/b;
flag = 1;
}
else if(flag)
{
cout << 0;
}
temp %= b;
// cout << temp << endl;
}
if(!flag)
{
cout << 0 << endl;
}
else
{
cout << " " << temp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐