Advertisement
jasonpogi1669

Karatsuba Trick using C++

Aug 13th, 2021
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int MOD = (int) 1e9 + 7;
  6.  
  7. long long Karatsuba(long long x, long long y) {
  8.     // ((10 ^ 6) * a + b) * ((10 ^ 6) * c + d)
  9.     // = ((10 ^ 12) * a * c) + ((10 ^ 6) * ((a * d) + (b * c))) + (b * d)
  10.     // where a, b, c, are (10 ^ 6)-digit numbers
  11.     long long a = x / 1000000;
  12.     long long b = x % 1000000;
  13.     long long c = y / 1000000;
  14.     long long d = y % 1000000;
  15.     // first expression = ((10 ^ 12) * a * c)
  16.     long long first_expression = ((1000000000000LL * a % MOD) * c) % MOD;
  17.     // second expression = ((10 ^ 6) * ((a * d) + (b * c)))
  18.     long long second_expression = (1000000 * (((a * d) + (b * c)) % MOD)) % MOD;
  19.     // third expression = (b * d)
  20.     long long third_expression = b * d;
  21.     return ((first_expression + second_expression + third_expression) % MOD);
  22. }
  23.  
  24. int main() {
  25.     // constraints: 1 <= x, y <= (10 ^ 12)
  26.     // note: answer must be computed to modulo ((10 ^ 9) + 7)
  27.     long long x, y;
  28.     cin >> x >> y;
  29.     cout << Karatsuba(x, y) << '\n';
  30.     return 0;
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement