Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <vector>
  4. #include <stdio.h>
  5. #include <cstdlib>
  6. #include <sstream>
  7. using namespace std;
  8.  
  9. class BigNum {
  10. public:
  11.   BigNum() {
  12.     buf_.push_back(0);
  13.   }
  14.  
  15.   explicit BigNum(const string& s) {
  16.     size_t i = s.size();
  17.     while (i > 9) {
  18.       buf_.push_back(stoul(s.substr(i - 9, 9)));
  19.       i -= 9;
  20.     }
  21.     if (i > 0)
  22.       buf_.push_back(stoul(s.substr(0, i)));
  23.  
  24.     if (!buf_.size())
  25.       buf_.push_back(0);
  26.   }
  27.  
  28.   BigNum(const BigNum& other) {
  29.     buf_ = other.buf_;
  30.   }
  31.  
  32.   BigNum& operator=(const BigNum& other) {
  33.     buf_ = other.buf_;
  34.     return *this;
  35.   }
  36.  
  37.   friend BigNum operator*(const BigNum& a, const BigNum& b) {
  38.     BigNum c("0");
  39.     c.buf_.resize(0);
  40.     c.buf_.resize(a.buf_.size() + b.buf_.size());
  41.  
  42.     for (size_t i = 0; i < a.buf_.size(); ++i)
  43.       for (size_t j = 0, carry = 0;
  44.            j < b.buf_.size() || carry;
  45.            ++j) {
  46.       carry += c.buf_[i + j];
  47.       carry += a.buf_[i] * ((j < b.buf_.size()) ? b.buf_[j] : 0);
  48.  
  49.       c.buf_[i + j] = uint32_t(carry % a.BASE);
  50.       carry /= a.BASE;
  51.     }
  52.  
  53.     while (c.buf_.size() > 1 && c.buf_.back() == 0)
  54.       c.buf_.pop_back();
  55.  
  56.     return c;
  57.   }
  58.  
  59.   friend ostream& operator<<(ostream& os, const BigNum& a) {
  60.     if (!a.buf_.size()) return os;
  61.     os << a.buf_.back();
  62.     for (auto it = ++a.buf_.rbegin();
  63.          it != a.buf_.rend();
  64.          ++it) {
  65.       os << setfill('0') << setw(9) << *it;
  66.     }
  67.  
  68.     return os;
  69.   }
  70. private:
  71.   const uint32_t BASE = 1000000000;
  72.   vector<uint32_t> buf_;
  73. };
  74.  
  75. BigNum longFactorial(int N) {
  76.   BigNum result("1");
  77.  
  78.   for (int i = 2; i <= N; i++) {
  79.     result = result * BigNum(to_string(i));
  80.   }
  81.   return result;
  82. }
  83.  
  84. int main() {   //факториал 100 (100!) на длинной арифметике
  85.   BigNum fact = longFactorial(10);
  86.   cout << fact << endl;
  87.   system("PAUSE");
  88.   return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement