大數乘法:兩int(4字節)相乘時,若兩個數都比較大,結果用一個int(4字節)存放不了,會產生溢出,導致結果不準確。因此需要對此類比較大的數的乘法另外想辦法。這就是大數乘法。大數乘法在ACM大賽,華爲,BAT的筆試面試題都比較經常出現。
以下是大數乘法的一種實現方法:
#include<iostream>
using namespace std;
#include <string.h>
#define N 100
/*
*將在數組中保存的字符串轉成數字存到int數組中
*/
void getdigits(int *a,char *s)
{
int i;
char digit;
int len = strlen(s);
//對數組初始化
for(i = 0; i < N; ++i)
*(a + i) = 0;
for(i = 0; i < len; ++i){
digit = *(s + i);
*(a + len - 1 - i) = digit - '0';//字符串s="12345",因此第一個字符應該存在int數組的最後一個位置
}
}
/*
*將數組a與數組b逐位相乘以後存入數組c
*/
void multiply(int *a,int *b,int *c)
{
int i,j;
//數組初始化
for(i = 0; i < 2 * N; ++i)
*(c + i) = 0;
/*
*數組a中的每位逐位與數組b相乘,並把結果存入數組c
*比如,12345*12345,a中的5與12345逐位相乘
*對於數組c:*(c+i+j)在i=0,j=0,1,2,3,4時存的是5與各位相乘的結果
*而在i=1,j=0,1,2,3,4時不光會存4與各位相乘的結果,還會累加上上次相乘的結果.這一點是需要注意的!!!
*/
for(i = 0; i < N; ++i)
for(j = 0; j < N; ++j)
*(c + i + j) += *(a + i) * *(b + j);
/*
*這裏是移位、進位
*/
for(i = 0; i < 2 * N - 1; ++i)
{
*(c + i + 1) += *(c + i)/10;//將十位上的數向前進位,並加上原來這個位上的數
*(c + i) = *(c + i)%10;//將剩餘的數存原來的位置上
}
}
int main()
{
int a[N],b[N],c[2*N];
char s1[N],s2[N];
int j = 2*N-1;
int i;
cout<<"input the first number:";
cin>>s1;
cout<<"input the second number:";
cin>>s2;
getdigits(a,s1);
getdigits(b,s2);
multiply(a,b,c);
while(c[j] == 0)
j--;
cout<<"the result is:";
for(i = j;i >= 0; --i)
cout<<c[i];
cout<<endl;
return 0;
}