大数乘法

自己写的一个大数乘法,效率还行~~

 

#include <stdio.h> #include <string.h> #define DIGIT 2 //num length of a array unit #define MAXDIGIT 100 //10^DIGIT, max-1 of a array unit #define MAX 1000 //Max of array #define LL long //type of num struct BigInt { LL data[MAX]; int size; }; //把string类型转换为BigInt类型 BigInt StrToBigInt(char *str) { int i,j,k; LL sum; BigInt ret; memset(&ret, 0, sizeof(ret)); int len; len = strlen(str); i=0;k=0; while (len-i>=DIGIT) { sum = 0; for (j=len-i-DIGIT;j<len-i;j++) sum = sum*10+(str[j]-'0'); ret.data[k++] = sum; i+=DIGIT; } if (i<len) { sum = 0; for (j=0;j<len-i;j++) sum = sum*10+(str[j]-'0'); ret.data[k++] = sum; } ret.size = k; return ret; } BigInt BigIntMul(BigInt a, BigInt b) { BigInt ret; memset(&ret, 0, sizeof(ret)); if (a.size == 1&&a.data[0] == 0) { ret.data[0] = 0;ret.size = 1;return ret; } if (b.size == 1&&b.data[0] == 0) { ret.data[0] = 0;ret.size = 1;return ret; } int i,j; for (i=0;i<a.size;i++) { for (j=0;j<b.size;j++) { ret.data[i+j] += b.data[j] * a.data[i]; ret.data[i+j+1] += ret.data[i+j] / MAXDIGIT; ret.data[i+j] = ret.data[i+j] % MAXDIGIT; } } ret.size = i+j; if (ret.data[ret.size]!=0) ret.size++; while(ret.data[ret.size-1]==0) ret.size--; return ret; } void PrintBigInt(BigInt a) { int i; if (a.data[a.size-1]!=0||a.size==1) printf("%d",a.data[a.size-1]); for (i=a.size-2;i>=0;i--) { int w = MAXDIGIT / 10; while (w > 1) { if (a.data[i] >= w) break; printf("0"); w /= 10; } printf("%d",a.data[i]); } printf("/n"); } int main() { char a[300], b[300]; BigInt BigNum_a, BigNum_b, BigNum_c; while (scanf("%s%s", a,b)!=EOF) { BigNum_a = StrToBigInt(a); BigNum_b = StrToBigInt(b); BigNum_c = BigIntMul(BigNum_a, BigNum_b); PrintBigInt(BigNum_c); } return 0; }

你可能感兴趣的:(c,String)