⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bigunsigned.cc

📁 实现了大整数的四则运算的基础类,BIgInt类的设计与实现
💻 CC
📖 第 1 页 / 共 2 页
字号:
/** Matt McCutchen's Big Integer Library*/#include "BigUnsigned.hh"// The "management" routines that used to be here are now in NumberlikeArray.hh./** The steps for construction of a BigUnsigned* from an integral value x are as follows:* 1. If x is zero, create an empty BigUnsigned and stop.* 2. If x is negative, throw an exception.* 3. Allocate a one-block number array.* 4. If x is of a signed type, convert x to the unsigned*    type of the same length.* 5. Expand x to a Blk, and store it in the number array.** Since 2005.01.06, NumberlikeArray uses `NULL' rather* than a real array if one of zero length is needed.* These constructors implicitly call NumberlikeArray's* default constructor, which sets `blk = NULL, cap = len = 0'.* So if the input number is zero, they can just return.* See remarks in `NumberlikeArray.hh'.*/BigUnsigned::BigUnsigned(unsigned long x) {	if (x == 0)		; // NumberlikeArray already did all the work	else {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	}}BigUnsigned::BigUnsigned(long x) {	if (x == 0)		;	else if (x > 0) {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	} else	throw "BigUnsigned::BigUnsigned(long): Cannot construct a BigUnsigned from a negative number";}BigUnsigned::BigUnsigned(unsigned int x) {	if (x == 0)		;	else {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	}}BigUnsigned::BigUnsigned(int x) {	if (x == 0)		;	else if (x > 0) {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	} else	throw "BigUnsigned::BigUnsigned(int): Cannot construct a BigUnsigned from a negative number";}BigUnsigned::BigUnsigned(unsigned short x) {	if (x == 0)		;	else {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	}}BigUnsigned::BigUnsigned(short x) {	if (x == 0)		;	else if (x > 0) {		cap = 1;		blk = new Blk[1];		len = 1;		blk[0] = Blk(x);	} else	throw "BigUnsigned::BigUnsigned(short): Cannot construct a BigUnsigned from a negative number";}// CONVERTERS/** The steps for conversion of a BigUnsigned to an* integral type are as follows:* 1. If the BigUnsigned is zero, return zero.* 2. If it is more than one block long or its lowest*    block has bits set out of the range of the target*    type, throw an exception.* 3. Otherwise, convert the lowest block to the*    target type and return it.*/namespace {	// These masks are used to test whether a Blk has bits	// set out of the range of a smaller integral type.  Note	// that this range is not considered to include the sign bit.	const BigUnsigned::Blk  lMask = ~0 >> 1;	const BigUnsigned::Blk uiMask = (unsigned int)(~0);	const BigUnsigned::Blk  iMask = uiMask >> 1;	const BigUnsigned::Blk usMask = (unsigned short)(~0);	const BigUnsigned::Blk  sMask = usMask >> 1;}BigUnsigned::operator unsigned long() const {	if (len == 0)		return 0;	else if (len == 1)		return (unsigned long) blk[0];	else		throw "BigUnsigned::operator unsigned long: Value is too big for an unsigned long";}BigUnsigned::operator long() const {	if (len == 0)		return 0;	else if (len == 1 && (blk[0] & lMask) == blk[0])		return (long) blk[0];	else		throw "BigUnsigned::operator long: Value is too big for a long";}BigUnsigned::operator unsigned int() const {	if (len == 0)		return 0;	else if (len == 1 && (blk[0] & uiMask) == blk[0])		return (unsigned int) blk[0];	else		throw "BigUnsigned::operator unsigned int: Value is too big for an unsigned int";}BigUnsigned::operator int() const {	if (len == 0)		return 0;	else if (len == 1 && (blk[0] & iMask) == blk[0])		return (int) blk[0];	else		throw "BigUnsigned::operator int: Value is too big for an int";}BigUnsigned::operator unsigned short() const {	if (len == 0)		return 0;	else if (len == 1 && (blk[0] & usMask) == blk[0])		return (unsigned short) blk[0];	else		throw "BigUnsigned::operator unsigned short: Value is too big for an unsigned short";}BigUnsigned::operator short() const {	if (len == 0)		return 0;	else if (len == 1 && (blk[0] & sMask) == blk[0])		return (short) blk[0];	else		throw "BigUnsigned::operator short: Value is too big for a short";}// COMPARISONBigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {	// A bigger length implies a bigger number.	if (len < x.len)		return less;	else if (len > x.len)		return greater;	else {		// Compare blocks one by one from left to right.		Index i = len;		while (i > 0) {			i--;			if (blk[i] == x.blk[i])				continue;			else if (blk[i] > x.blk[i])				return greater;			else				return less;		}		// If no blocks differed, the numbers are equal.		return equal;	}}// PUT-HERE OPERATIONS/** Below are implementations of the four basic arithmetic operations* for `BigUnsigned's.  Their purpose is to use a mechanism that can* calculate the sum, difference, product, and quotient/remainder of* two individual blocks in order to calculate the sum, difference,* product, and quotient/remainder of two multi-block BigUnsigned* numbers.** As alluded to in the comment before class `BigUnsigned',* these algorithms bear a remarkable similarity (in purpose, if* not in implementation) to the way humans operate on big numbers.* The built-in `+', `-', `*', `/' and `%' operators are analogous* to elementary-school ``math facts'' and ``times tables''; the* four routines below are analogous to ``long division'' and its* relatives.  (Only a computer can ``memorize'' a times table with* 18446744073709551616 entries!  (For 32-bit blocks.))** The discovery of these four algorithms, called the ``classical* algorithms'', marked the beginning of the study of computer science.* See Section 4.3.1 of Knuth's ``The Art of Computer Programming''.*//* * On most calls to put-here operations, it's safe to read the inputs little by * little and write the outputs little by little.  However, if one of the * inputs is coming from the same variable into which the output is to be * stored (an "aliased" call), we risk overwriting the input before we read it. * In this case, we first compute the result into a temporary BigUnsigned * variable and then copy it into the requested output variable *this. * Each put-here operation uses the DTRT_ALIASED macro (Do The Right Thing on * aliased calls) to generate code for this check. *  * I adopted this approach on 2007.02.13 (see Assignment Operators in * BigUnsigned.hh).  Before then, put-here operations rejected aliased calls * with an exception.  I think doing the right thing is better. *  * Some of the put-here operations can probably handle aliased calls safely * without the extra copy because (for example) they process blocks strictly * right-to-left.  At some point I might determine which ones don't need the * copy, but my reasoning would need to be verified very carefully.  For now * I'll leave in the copy. */#define DTRT_ALIASED(cond, op) \	if (cond) { \		BigUnsigned tmpThis; \		tmpThis.op; \		*this = tmpThis; \		return; \	}// Additionvoid BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {	DTRT_ALIASED(this == &a || this == &b, add(a, b));	// If one argument is zero, copy the other.	if (a.len == 0) {		operator =(b);		return;	} else if (b.len == 0) {		operator =(a);		return;	}	// Some variables...	// Carries in and out of an addition stage	bool carryIn, carryOut;	Blk temp;	Index i;	// a2 points to the longer input, b2 points to the shorter	const BigUnsigned *a2, *b2;	if (a.len >= b.len) {		a2 = &a;		b2 = &b;	} else {		a2 = &b;		b2 = &a;	}	// Set prelimiary length and make room in this BigUnsigned	len = a2->len + 1;	allocate(len);	// For each block index that is present in both inputs...	for (i = 0, carryIn = false; i < b2->len; i++) {		// Add input blocks		temp = a2->blk[i] + b2->blk[i];		// If a rollover occurred, the result is less than either input.		// This test is used many times in the BigUnsigned code.		carryOut = (temp < a2->blk[i]);		// If a carry was input, handle it		if (carryIn) {			temp++;			carryOut |= (temp == 0);		}		blk[i] = temp; // Save the addition result		carryIn = carryOut; // Pass the carry along	}	// If there is a carry left over, increase blocks until	// one does not roll over.	for (; i < a2->len && carryIn; i++) {		temp = a2->blk[i] + 1;		carryIn = (temp == 0);		blk[i] = temp;	}	// If the carry was resolved but the larger number	// still has blocks, copy them over.	for (; i < a2->len; i++)		blk[i] = a2->blk[i];	// Set the extra block if there's still a carry, decrease length otherwise	if (carryIn)		blk[i] = 1;	else		len--;}// Subtractionvoid BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {	DTRT_ALIASED(this == &a || this == &b, subtract(a, b));	// If b is zero, copy a.  If a is shorter than b, the result is negative.	if (b.len == 0) {		operator =(a);		return;	} else if (a.len < b.len)	throw "BigUnsigned::subtract: Negative result in unsigned calculation";	// Some variables...	bool borrowIn, borrowOut;	Blk temp;	Index i;	// Set preliminary length and make room	len = a.len;	allocate(len);	// For each block index that is present in both inputs...	for (i = 0, borrowIn = false; i < b.len; i++) {		temp = a.blk[i] - b.blk[i];		// If a reverse rollover occurred, the result is greater than the block from a.		borrowOut = (temp > a.blk[i]);		// Handle an incoming borrow		if (borrowIn) {			borrowOut |= (temp == 0);			temp--;		}		blk[i] = temp; // Save the subtraction result		borrowIn = borrowOut; // Pass the borrow along	}	// If there is a borrow left over, decrease blocks until	// one does not reverse rollover.	for (; i < a.len && borrowIn; i++) {		borrowIn = (a.blk[i] == 0);		blk[i] = a.blk[i] - 1;	}	// If there's still a borrow, the result is negative.	// Throw an exception, but zero out this object first just in case.	if (borrowIn) {		len = 0;		throw "BigUnsigned::subtract: Negative result in unsigned calculation";	} else // Copy over the rest of the blocks	for (; i < a.len; i++)		blk[i] = a.blk[i];	// Zap leading zeros	zapLeadingZeros();}/** About the multiplication and division algorithms:** I searched unsucessfully for fast built-in operations like the `b_0'* and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer* Programming'' (replace `place' by `Blk'):**    ``b_0[:] multiplication of a one-place integer by another one-place*      integer, giving a two-place answer;**    ``c_0[:] division of a two-place integer by a one-place integer,*      provided that the quotient is a one-place integer, and yielding*      also a one-place remainder.''** I also missed his note that ``[b]y adjusting the word size, if* necessary, nearly all computers will have these three operations* available'', so I gave up on trying to use algorithms similar to his.* A future version of the library might include such algorithms; I* would welcome contributions from others for this.** I eventually decided to use bit-shifting algorithms.  To multiply `a'* and `b', we zero out the result.  Then, for each `1' bit in `a', we* shift `b' left the appropriate amount and add it to the result.* Similarly, to divide `a' by `b', we shift `b' left varying amounts,* repeatedly trying to subtract it from `a'.  When we succeed, we note* the fact by setting a bit in the quotient.  While these algorithms* have the same O(n^2) time complexity as Knuth's, the ``constant factor''* is likely to be larger.** Because I used these algorithms, which require single-block addition* and subtraction rather than single-block multiplication and division,* the innermost loops of all four routines are very similar.  Study one* of them and all will become clear.*//** This is a little inline function used by both the multiplication* routine and the division routine.** `getShiftedBlock' returns the `x'th block of `num << y'.* `y' may be anything from 0 to N - 1, and `x' may be anything from* 0 to `num.len'.** Two things contribute to this block:** (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.** (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.** But we must be careful if `x == 0' or `x == num.len', in* which case we should use 0 instead of (2) or (1), respectively.** If `y == 0', then (2) contributes 0, as it should.  However,* in some computer environments, for a reason I cannot understand,* `a >> b' means `a >> (b % N)'.  This means `num.blk[x-1] >> (N - y)'* will return `num.blk[x-1]' instead of the desired 0 when `y == 0';* the test `y == 0' handles this case specially.*/inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,	BigUnsigned::Index x, unsigned int y) {	BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));	BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);	return part1 | part2;}// Multiplicationvoid BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {	DTRT_ALIASED(this == &a || this == &b, multiply(a, b));	// If either a or b is zero, set to zero.	if (a.len == 0 || b.len == 0) {		len = 0;		return;	}	/*	* Overall method:	*	* Set this = 0.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -