分析:
大数能大到整形类型存储不了。须要借助于其它的算法,来完毕乘法运算。
能够使用口算乘法的步骤来模拟乘法操作。例如以下:
123
* 122
=
3 4 6
+ 3 4 6
+ 1 2 3
= 1 5 0 0 6
实现例如以下:
#include<iostream> #include<string.h> using namespace std; char* MutiBigerNum(char* a, char* b) { int len1 = strlen(a); int len2 = strlen(b); char* res = new char[len1 + len2 + 1]; memset(res, '0', len1+len2); for(int i=len1-1; i >= 0; i-- ) { int carry = 0; for(int j = len2 -1; j >= 0; j--) { int temp = (res[i + j+ 1] - '0') + carry + (a[i] - '0')*(b[j] - '0'); carry = 0; if(temp >= 10) { carry = temp/10; } res[i+j+1] = temp%10 + '0'; } res[i] = carry + '0'; } return res; } int main(int argn, char** argv) { char *a = "122"; char *b = "123"; if(argn > 2) { a = argv[1]; b = argv[2]; } char* resnum = MutiBigerNum(a, b); if(strlen(resnum) > 0 && resnum[0] == '0') cout << a << "*" << b << "=" << resnum + 1 << endl; else cout << a << "*" << b << "=" << resnum << endl; return 0; }
执行结果例如以下:
./test
122*123=15006
./test 999 888
999*888=887112