//Filename: LongMuli.cpp //Date: 2009-11-9 15:49:18 #include <stdio.h> #include <string.h> void reverse(char* a) { int longth = strlen(a); char t=0; for ( int i=0; i<longth/2; i++ ) { t = a[i]; a[i] = a[longth-i-1]; a[longth-i-1] = t; } } void mult(char* op1, char* op2, char* ans) { int top1s = strlen(op1); int top2s = strlen(op2); char* top1=NULL; char* top2=NULL; if ( top1s<12 ) { top1 = new char[12]; } else { top1 = new char[top1s+1]; } if ( top2s<12 ) { top2 = new char[12]; } else { top2 = new char[top2s+1]; } strcpy(top1, op1); strcpy(top2, op2); reverse(top1); reverse(top2); for ( int k = 0; k<top1s+top2s; k++ ) { ans[k] = '0'; } int i,j; int jw,ys; for ( j = 0; j<top2s; j++ ) { jw = 0; for ( i = 0; i<top1s; i++ ) { ys = ((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')%10; jw = ((top1[i]-'0')*(top2[j]-'0')+jw+ans[i+j]-'0')/10; ans[i+j] = ys+'0'; } if (jw>0) { ans[i+j] = jw+'0'; } } int longth = i+j-1; if (jw>0) { ans[longth++] = jw+'0'; } ans[longth] = '/0'; reverse(ans); delete[] top2; delete[] top1; } void usage() { printf("//-----超长正整数乘法运算器-----/r/n"); printf("使用方法:LongMuli.exe 乘数 被乘数/r/n"); } int main(int argc, char** argv) { if ( argc!= 3 ) { usage(); return -1; } char* num1 = argv[1]; char* num2 = argv[2]; int len = strlen(num1)+strlen(num2)+2; char* buf=NULL; if ( len<12 ) { buf = new char[12]; } else { buf = new char[len]; } mult(num1, num2, buf); printf("/r/n结果为:/r/n%s/r/n", buf); delete[] buf; return 0; }