biginteger.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // biginteger.h
  3. // bigdecimal
  4. //
  5. // Created by Sam Jaffe on 6/30/17.
  6. //
  7. #pragma once
  8. #include <string>
  9. #include <vector>
  10. namespace math {
  11. class biginteger {
  12. private:
  13. template <typename Int>
  14. using is_signed_t = typename std::enable_if<std::numeric_limits<Int>::is_integer && std::numeric_limits<Int>::is_signed, int>::type;
  15. template <typename Int>
  16. using is_unsigned_t = typename std::enable_if<std::numeric_limits<Int>::is_integer && !std::numeric_limits<Int>::is_signed, int>::type;
  17. public:
  18. using data_type = std::vector<int32_t>;
  19. static biginteger const ZERO, ONE, NEGATIVE_ONE;
  20. static constexpr int32_t const MAX_SEG { 999999999};
  21. static constexpr int32_t const OVER_SEG {1000000000};
  22. static constexpr int32_t const SEG_DIGITS{ 9};
  23. public:
  24. // Constructors
  25. biginteger();
  26. template <typename Int>
  27. biginteger(Int value, is_signed_t<Int> = 0)
  28. : biginteger(value < 0, static_cast<uint64_t>(value < 0 ? -value : value)) {}
  29. template <typename Int>
  30. biginteger(Int value, is_unsigned_t<Int> = 0)
  31. : biginteger(false, static_cast<uint64_t>(value)) {}
  32. biginteger(char const *);
  33. // Unary operators
  34. biginteger operator-() const;
  35. // Binary operators
  36. friend biginteger operator+(biginteger, biginteger const &);
  37. friend biginteger operator-(biginteger, biginteger const &);
  38. friend biginteger operator*(biginteger, biginteger const &);
  39. friend biginteger operator/(biginteger, biginteger const &);
  40. friend biginteger operator%(biginteger, biginteger const &);
  41. friend biginteger & operator+=(biginteger &, biginteger const &);
  42. friend biginteger & operator-=(biginteger &, biginteger const &);
  43. friend biginteger & operator*=(biginteger &, biginteger const &);
  44. friend biginteger & operator/=(biginteger &, biginteger const &);
  45. // Output
  46. std::string to_string() const;
  47. // Comparison
  48. friend bool operator==(biginteger const &, biginteger const &);
  49. friend bool operator!=(biginteger const &, biginteger const &);
  50. friend bool operator<=(biginteger const &, biginteger const &);
  51. friend bool operator< (biginteger const &, biginteger const &);
  52. friend bool operator>=(biginteger const &, biginteger const &);
  53. friend bool operator> (biginteger const &, biginteger const &);
  54. private:
  55. biginteger(bool, uint64_t);
  56. void subtract_impl(biginteger const & lhs, bool is_sub);
  57. friend void swap(biginteger & rhs, biginteger & lhs) {
  58. using std::swap;
  59. swap(rhs.is_negative, lhs.is_negative);
  60. swap(rhs.data, lhs.data);
  61. }
  62. bool is_negative;
  63. data_type data{};
  64. };
  65. }