大数相乘
sum中,高位在前,所以两个乘数必须先转换一下,即末位在前,依此类推。
1 #include<stdio.h> 2 #include<string.h> 3 const int maxn = 505; 4 char a[ maxn ],b[ maxn ]; 5 int sum[ maxn*2 ]; 6 void change ( int lena,int lenb ){ 7 int k=0; 8 char tmp[ maxn ]; 9 for( int i=lena-1;i>=0;i-- ) 10 tmp[ k++ ]=a[ i ]; 11 for( int i=0;i<lena;i++ ) 12 a[ i ]=tmp[ i ]; 13 k=0; 14 for( int i=lenb-1;i>=0;i-- ) 15 tmp[ k++ ]=b[ i ]; 16 for( int i=0;i<lenb;i++ ) 17 b[ i ]=tmp[ i ]; 18 } 19 int main(){ 20 int T; 21 scanf("%d",&T); 22 getchar(); 23 while( T-- ){ 24 memset( sum,0,sizeof( sum ) ); 25 scanf("%s%s",a,b); 26 if( a[ 0 ]=='0'||b[ 0 ]=='0' ){ 27 printf("0\n"); 28 continue; 29 } 30 int lena,lenb; 31 lena=strlen( a ),lenb=strlen( b ); 32 change ( lena,lenb );//a,b倒置 33 for( int i=0;i<lena;i++ ){ 34 for( int j=0;j<lenb;j++ ){ 35 sum[ i+j ]+=( a[ i ]-'0' )*( b[ j ]-'0' ); 36 } 37 } 38 int k; 39 int delta=5;//可任意 40 for( k=1;k<lena+lenb+delta;k++ ){ 41 sum[ k ]+=sum[ k-1 ]/10; 42 sum[ k-1 ]%=10; 43 } 44 for( ;k>=0;k-- ) 45 if( sum[ k ]==0 ) continue; 46 else break; 47 for( ;k>=0;k-- ) 48 printf("%d",sum[ k ]); 49 printf("\n"); 50 } 51 return 0; 52 }