这是一道新浪的笔试题,计算两个很大的数相乘并输出结果.思路是采取分解两个大数,将它们写成(a1*10^n1 + a2*10^n2…..)*(b1*10^n1 + b2*10^n2…..)的形式,然后计算a1b1,a2b2…,然后加上权重,最后加起来.算法的时间界是(N1*N2/M^2),N1,N2是输入的位数.
#include "iostream"
#include "string"
#include "vector"
#include "algorithm"
#include "memory"
#include "set"
using namespace std;
const int M = 6;
void add(string & ans, string temp);
int main()
{
string x, y;
cout << "please enter two interger:\n";
while (cin >> x >> y)
{
string ans(x.size()+y.size()+1,'0');
string sub_x, sub_y;
size_t pos_x = 0;
while (pos_x < x.size())
{
sub_x = x.substr(pos_x, M);
size_t pos_y = 0;
while (pos_y < y.size())
{
sub_y = y.substr(pos_y, M);
size_t weight = x.size()-pos_x-sub_x.size()+y.size()-pos_y-sub_y.size();
long long temp_result = stod(sub_x)*stod(sub_y);
if (temp_result)
add(ans, to_string(temp_result)+string(weight,'0'));
pos_y += M;
}
pos_x += M;
}
cout<<endl<<string(ans.find_first_not_of('0') + ans.begin(), ans.end());
}
return 0;
}
void add(string & ans, string temp)
{
reverse(ans.begin(), ans.end());
reverse(temp.begin(), temp.end());
size_t c = 0;
for (size_t i = temp.find_first_not_of('0'); i != temp.size(); ++i)
{
size_t bit_ans = c + temp[i] + (0 - '0') + ans[i] +(0 - '0');
c = bit_ans / 10;
ans[i] = bit_ans - c*10 + ('0'-0);
}
for (size_t i = temp.size(); c!=0; ++i)
{
size_t bit_ans = ans[i]+(0-'0') + c;
c = bit_ans / 10;
ans[i] = bit_ans - c*10 + ('0' - 0);
}
reverse(ans.begin(), ans.end());
}
