Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template< class BaseType >
- class BigInt
- {
- typedef typename BaseType BT;
- protected: std::vector< BaseType > value_;
- };
- template< class BaseType >
- BigInt< BaseType >& BigInt< BaseType >::operator += (BigInt< BaseType > const& operand)
- {
- BT count, carry = 0;
- for (count = 0; count < std::max(value_.size(), operand.value_.size(); count++)
- {
- BT op0 = count < value_.size() ? value_.at(count) : 0,
- op1 = count < operand.value_.size() ? operand.value_.at(count) : 0;
- BT digits_result = op0 + op1 + carry;
- if (digits_result-carry < std::max(op0, op1)
- {
- BT carry_old = carry;
- carry = digits_result;
- digits_result = (op0 + op1 + carry) >> sizeof(BT)*8; // NOTE [1]
- }
- else carry = 0;
- }
- return *this;
- }
- // NOTE 1: I did not test this code. And I am not sure if this will work; if it does
- // not, then you must restrict BaseType to be the second biggest type
- // available, i.e. a 32-bit int when you have a 64-bit long. Then use
- // a temporary or a cast to the mightier type and retrieve the upper bits.
- // Or you do it bitwise. ;-)
- typedef struct {
- int high, low;
- } BiggerInt;
- BiggerInt add( const BiggerInt *lhs, const BiggerInt *rhs ) {
- BiggerInt ret;
- /* Ideally, you'd want a better way to check for overflow conditions */
- if ( rhs->high < INT_MAX - lhs->high ) {
- /* With a variable-length (a real) BigInt, you'd allocate some more room here */
- }
- ret.high = lhs->high + rhs->high;
- if ( rhs->low < INT_MAX - lhs->low ) {
- /* No overflow */
- ret.low = lhs->low + rhs->low;
- }
- else {
- /* Overflow */
- ret.high += 1;
- ret.low = lhs->low - ( INT_MAX - rhs->low ); /* Right? */
- }
- return ret;
- }
Add Comment
Please, Sign In to add comment