📄 bigunsigned.cc
字号:
carryOut = (temp < blk[k]); if (carryIn) { temp++; carryOut |= (temp == 0); } blk[k] = temp; carryIn = carryOut; } // No more extra iteration to deal with `bHigh'. // Roll-over a carry as necessary. for (; carryIn; k++) { blk[k]++; carryIn = (blk[k] == 0); } } } // Zap possible leading zero if (blk[len - 1] == 0) len--;}/* * DIVISION WITH REMAINDER * This monstrous function mods *this by the given divisor b while storing the * quotient in the given object q; at the end, *this contains the remainder. * The seemingly bizarre pattern of inputs and outputs was chosen so that the * function copies as little as possible (since it is implemented by repeated * subtraction of multiples of b from *this). * * "modWithQuotient" might be a better name for this function, but I would * rather not change the name now. */void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) { /* Defending against aliased calls is more complex than usual because we * are writing to both *this and q. * * It would be silly to try to write quotient and remainder to the * same variable. Rule that out right away. */ if (this == &q) throw "BigUnsigned::divideWithRemainder: Cannot write quotient and remainder into the same variable"; /* Now *this and q are separate, so the only concern is that b might be * aliased to one of them. If so, use a temporary copy of b. */ if (this == &b || &q == &b) { BigUnsigned tmpB(b); divideWithRemainder(tmpB, q); return; } /* * Knuth's definition of mod (which this function uses) is somewhat * different from the C++ definition of % in case of division by 0. * * We let a / 0 == 0 (it doesn't matter much) and a % 0 == a, no * exceptions thrown. This allows us to preserve both Knuth's demand * that a mod 0 == a and the useful property that * (a / b) * b + (a % b) == a. */ if (b.len == 0) { q.len = 0; return; } /* * If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into * *this at all. The quotient is 0 and *this is already the remainder (so leave it alone). */ if (len < b.len) { q.len = 0; return; } // At this point we know (*this).len >= b.len > 0. (Whew!) /* * Overall method: * * For each appropriate i and i2, decreasing: * Subtract (b << (i blocks and i2 bits)) from *this, storing the * result in subtractBuf. * If the subtraction succeeds with a nonnegative result: * Turn on bit i2 of block i of the quotient q. * Copy subtractBuf back into *this. * Otherwise bit i2 of block i remains off, and *this is unchanged. * * Eventually q will contain the entire quotient, and *this will * be left with the remainder. * * subtractBuf[x] corresponds to blk[x], not blk[x+i], since 2005.01.11. * But on a single iteration, we don't touch the i lowest blocks of blk * (and don't use those of subtractBuf) because these blocks are * unaffected by the subtraction: we are subtracting * (b << (i blocks and i2 bits)), which ends in at least `i' zero * blocks. */ // Variables for the calculation Index i, j, k; unsigned int i2; Blk temp; bool borrowIn, borrowOut; /* * Make sure we have an extra zero block just past the value. * * When we attempt a subtraction, we might shift `b' so * its first block begins a few bits left of the dividend, * and then we'll try to compare these extra bits with * a nonexistent block to the left of the dividend. The * extra zero block ensures sensible behavior; we need * an extra block in `subtractBuf' for exactly the same reason. */ Index origLen = len; // Save real length. /* To avoid an out-of-bounds access in case of reallocation, allocate * first and then increment the logical length. */ allocateAndCopy(len + 1); len++; blk[origLen] = 0; // Zero the added block. // subtractBuf holds part of the result of a subtraction; see above. Blk *subtractBuf = new Blk[len]; // Set preliminary length for quotient and make room q.len = origLen - b.len + 1; q.allocate(q.len); // Zero out the quotient for (i = 0; i < q.len; i++) q.blk[i] = 0; // For each possible left-shift of b in blocks... i = q.len; while (i > 0) { i--; // For each possible left-shift of b in bits... // (Remember, N is the number of bits in a Blk.) q.blk[i] = 0; i2 = N; while (i2 > 0) { i2--; /* * Subtract b, shifted left i blocks and i2 bits, from *this, * and store the answer in subtractBuf. In the for loop, `k == i + j'. * * Compare this to the middle section of `multiply'. They * are in many ways analogous. See especially the discussion * of `getShiftedBlock'. */ for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) { temp = blk[k] - getShiftedBlock(b, j, i2); borrowOut = (temp > blk[k]); if (borrowIn) { borrowOut |= (temp == 0); temp--; } // Since 2005.01.11, indices of `subtractBuf' directly match those of `blk', so use `k'. subtractBuf[k] = temp; borrowIn = borrowOut; } // No more extra iteration to deal with `bHigh'. // Roll-over a borrow as necessary. for (; k < origLen && borrowIn; k++) { borrowIn = (blk[k] == 0); subtractBuf[k] = blk[k] - 1; } /* * If the subtraction was performed successfully (!borrowIn), * set bit i2 in block i of the quotient. * * Then, copy the portion of subtractBuf filled by the subtraction * back to *this. This portion starts with block i and ends-- * where? Not necessarily at block `i + b.len'! Well, we * increased k every time we saved a block into subtractBuf, so * the region of subtractBuf we copy is just [i, k). */ if (!borrowIn) { q.blk[i] |= (Blk(1) << i2); while (k > i) { k--; blk[k] = subtractBuf[k]; } } } } // Zap possible leading zero in quotient if (q.blk[q.len - 1] == 0) q.len--; // Zap any/all leading zeros in remainder zapLeadingZeros(); // Deallocate subtractBuf. // (Thanks to Brad Spencer for noticing my accidental omission of this!) delete [] subtractBuf;}/* BITWISE OPERATORS * These are straightforward blockwise operations except that they differ in * the output length and the necessity of zapLeadingZeros. */void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) { DTRT_ALIASED(this == &a || this == &b, bitAnd(a, b)); // The bitwise & can't be longer than either operand. len = (a.len >= b.len) ? b.len : a.len; allocate(len); Index i; for (i = 0; i < len; i++) blk[i] = a.blk[i] & b.blk[i]; zapLeadingZeros();}void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) { DTRT_ALIASED(this == &a || this == &b, bitOr(a, b)); Index i; const BigUnsigned *a2, *b2; if (a.len >= b.len) { a2 = &a; b2 = &b; } else { a2 = &b; b2 = &a; } allocate(a2->len); for (i = 0; i < b2->len; i++) blk[i] = a2->blk[i] | b2->blk[i]; for (; i < a2->len; i++) blk[i] = a2->blk[i]; len = a2->len; // Doesn't need zapLeadingZeros.}void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) { DTRT_ALIASED(this == &a || this == &b, bitXor(a, b)); Index i; const BigUnsigned *a2, *b2; if (a.len >= b.len) { a2 = &a; b2 = &b; } else { a2 = &b; b2 = &a; } allocate(a2->len); for (i = 0; i < b2->len; i++) blk[i] = a2->blk[i] ^ b2->blk[i]; for (; i < a2->len; i++) blk[i] = a2->blk[i]; len = a2->len; zapLeadingZeros();}void BigUnsigned::bitShiftLeft(const BigUnsigned &a, int b) { DTRT_ALIASED(this == &a, bitShiftLeft(a, b)); if (b < 0) { if (b << 1 == 0) throw "BigUnsigned::bitShiftLeft: " "Pathological shift amount not implemented"; else { bitShiftRight(a, -b); return; } } Index shiftBlocks = b / N; unsigned int shiftBits = b % N; // + 1: room for high bits nudged left into another block len = a.len + shiftBlocks + 1; allocate(len); Index i, j; for (i = 0; i < shiftBlocks; i++) blk[i] = 0; for (j = 0, i = shiftBlocks; j <= a.len; j++, i++) blk[i] = getShiftedBlock(a, j, shiftBits); // Zap possible leading zero if (blk[len - 1] == 0) len--;}void BigUnsigned::bitShiftRight(const BigUnsigned &a, int b) { DTRT_ALIASED(this == &a, bitShiftRight(a, b)); if (b < 0) { if (b << 1 == 0) throw "BigUnsigned::bitShiftRight: " "Pathological shift amount not implemented"; else { bitShiftLeft(a, -b); return; } } // This calculation is wacky, but expressing the shift as a left bit shift // within each block lets us use getShiftedBlock. Index rightShiftBlocks = (b + N - 1) / N; unsigned int leftShiftBits = N * rightShiftBlocks - b; // Now (N * rightShiftBlocks - leftShiftBits) == b // and 0 <= leftShiftBits < N. if (rightShiftBlocks >= a.len + 1) { // All of a is guaranteed to be shifted off, even considering the left // bit shift. len = 0; return; } // Now we're allocating a positive amount. // + 1: room for high bits nudged left into another block len = a.len + 1 - rightShiftBlocks; allocate(len); Index i, j; for (j = rightShiftBlocks, i = 0; j <= a.len; j++, i++) blk[i] = getShiftedBlock(a, j, leftShiftBits); // Zap possible leading zero if (blk[len - 1] == 0) len--;}// INCREMENT/DECREMENT OPERATORS// Prefix incrementvoid BigUnsigned::operator ++() { Index i; bool carry = true; for (i = 0; i < len && carry; i++) { blk[i]++; carry = (blk[i] == 0); } if (carry) { // Allocate and then increase length, as in divideWithRemainder allocateAndCopy(len + 1); len++; blk[i] = 1; }}// Postfix increment: same as prefixvoid BigUnsigned::operator ++(int) { operator ++();}// Prefix decrementvoid BigUnsigned::operator --() { if (len == 0) throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero"; Index i; bool borrow = true; for (i = 0; borrow; i++) { borrow = (blk[i] == 0); blk[i]--; } // Zap possible leading zero (there can only be one) if (blk[len - 1] == 0) len--;}// Postfix decrement: same as prefixvoid BigUnsigned::operator --(int) { operator --();}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -