Advertisement
Josif_tepe

Untitled

Feb 22nd, 2024
1,085
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. string add_two_numbers(string a, string b) {
  7.     if(a.size() < b.size()) {
  8.         swap(a, b);
  9.     }
  10.     int carry = 0;
  11.     string res = "";
  12.     int i = (int) a.size() - 1, j = (int) b.size() - 1;
  13.     while(j >= 0 and i >= 0) {
  14.         int digit_a = (int) (a[i] - '0');
  15.         int digit_b = (int) (b[j] - '0');
  16.         int sum = digit_a + digit_b + carry;
  17.         if(sum < 10) {
  18.             carry = 0;
  19.         }
  20.         else {
  21.             carry = 1;
  22.             sum -= 10;
  23.         }
  24.         res += (sum + '0');
  25.         i--;
  26.         j--;
  27.     }
  28.     while(i >= 0) {
  29.         int digit_a = (int) (a[i] - '0');
  30.         int sum = digit_a + carry;
  31.         if(sum < 10) {
  32.             carry = 0;
  33.         }
  34.         else {
  35.             carry = 1;
  36.             sum -= 10;
  37.         }
  38.         res += (sum + '0');
  39.         i--;
  40.     }
  41.     if(carry == 1) {
  42.         res += "1";
  43.     }
  44.     reverse(res.begin(), res.end());
  45.     return res;
  46. }
  47. string multiply_two_numbers(string a, string b) {
  48.     vector<int> v((int) a.size() + (int) b.size(), 0);
  49.     int sz_a = (int) a.size();
  50.     int sz_b = (int) b.size();
  51.     for(int i = sz_a - 1; i >= 0; i--) {
  52.         for(int j = sz_b - 1; j >= 0; j--) {
  53.             v[i + j + 1] += (a[i] - '0') * (b[j] - '0');
  54.            
  55.         }
  56.     }
  57.     for(int i = sz_a + sz_b - 1; i >= 0; i--) {
  58.         if(v[i] >= 10) {
  59.             v[i - 1] += v[i] / 10;
  60.             v[i] %= 10;
  61.         }
  62.     }
  63.     string res = "";
  64.     int i = 0;
  65.     while(v[i] == 0) {
  66.         i++;
  67.     }
  68.     while(i < sz_a + sz_b) {
  69.         res += (v[i] + '0');
  70.         i++;
  71.     }
  72.    
  73.     return res;
  74. }
  75. int main() {
  76.     ios_base::sync_with_stdio(false);
  77.     int n;
  78.     cin >> n;
  79.     string power_of_two = "2";
  80.     string res = "0";
  81.     for(int i = 0; i < n; i++) {
  82.         res = add_two_numbers(res, power_of_two);
  83.         power_of_two = multiply_two_numbers(power_of_two, "2");
  84.     }
  85.     cout << res << endl;
  86.     return 0;
  87. }
  88.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement