文本是schindlerlee原创,查看原文请访问
www.cppblog.com/schindlerlee
转载请保留此信息,本人保留关于本文的一切信息
const int PRECISION = 525;
const int SENTINAL = 0x7fffffff;
struct bignum {
int s[PRECISION];
int len;
void reset() {
for (int i = 0; i < PRECISION; i++) {
s[i] = SENTINAL;
} len = 0;
}
};
void justify(bignum & a, int step)
/*
* 调整乘法产生的结果
* 例如将:
*-------------------------------------------------------------
*| 64 | 64 |SENT|SENT|SENT|SENT|SENT|SENT|SENT|SENT|SENT|SENT|
*-------------------------------------------------------------
*调整为
*-------------------------------------------------------------
*| 4 | 0 | 7 |SENT|SENT|SENT|SENT|SENT|SENT|SENT|SENT|SENT|
*-------------------------------------------------------------
* */
{
if (step < PRECISION && a.s[step] != SENTINAL) {
if (a.s[step] > 9) {
if (a.s[step + 1] == SENTINAL)
a.s[step + 1] = 0;
a.s[step + 1] += a.s[step] / 10;
a.s[step] = a.s[step] % 10;
}
justify(a, step + 1);
} else {
a.len = step;
for (int i = step; i < PRECISION; i++) {
a.s[i] = SENTINAL;
}
}
}
void mul(bignum a, bignum b, bignum & c) //a b result
{
int i, j;
c.reset();
for (i = 0; i < a.len; i++) {
for (j = 0; j < b.len; j++) {
if(i+j < PRECISION) {
if (c.s[i + j] == SENTINAL) c.s[i + j] = 0;
c.s[i + j] += a.s[i] * b.s[j];
}
}
}
justify(c, 0);
}