code_junkie

How to implement big int in C++

Nov 12th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. template< class BaseType >
  2. class BigInt
  3. {
  4. typedef typename BaseType BT;
  5. protected: std::vector< BaseType > value_;
  6. };
  7.  
  8. template< class BaseType >
  9. BigInt< BaseType >& BigInt< BaseType >::operator += (BigInt< BaseType > const& operand)
  10. {
  11. BT count, carry = 0;
  12. for (count = 0; count < std::max(value_.size(), operand.value_.size(); count++)
  13. {
  14. BT op0 = count < value_.size() ? value_.at(count) : 0,
  15. op1 = count < operand.value_.size() ? operand.value_.at(count) : 0;
  16. BT digits_result = op0 + op1 + carry;
  17. if (digits_result-carry < std::max(op0, op1)
  18. {
  19. BT carry_old = carry;
  20. carry = digits_result;
  21. digits_result = (op0 + op1 + carry) >> sizeof(BT)*8; // NOTE [1]
  22. }
  23. else carry = 0;
  24. }
  25.  
  26. return *this;
  27. }
  28. // NOTE 1: I did not test this code. And I am not sure if this will work; if it does
  29. // not, then you must restrict BaseType to be the second biggest type
  30. // available, i.e. a 32-bit int when you have a 64-bit long. Then use
  31. // a temporary or a cast to the mightier type and retrieve the upper bits.
  32. // Or you do it bitwise. ;-)
  33.  
  34. typedef struct {
  35. int high, low;
  36. } BiggerInt;
  37.  
  38. BiggerInt add( const BiggerInt *lhs, const BiggerInt *rhs ) {
  39. BiggerInt ret;
  40.  
  41. /* Ideally, you'd want a better way to check for overflow conditions */
  42. if ( rhs->high < INT_MAX - lhs->high ) {
  43. /* With a variable-length (a real) BigInt, you'd allocate some more room here */
  44. }
  45.  
  46. ret.high = lhs->high + rhs->high;
  47.  
  48. if ( rhs->low < INT_MAX - lhs->low ) {
  49. /* No overflow */
  50. ret.low = lhs->low + rhs->low;
  51. }
  52. else {
  53. /* Overflow */
  54. ret.high += 1;
  55. ret.low = lhs->low - ( INT_MAX - rhs->low ); /* Right? */
  56. }
  57.  
  58. return ret;
  59. }
Add Comment
Please, Sign In to add comment