Advertisement
maycod23

Untitled

Jun 20th, 2022
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. // get prime factors of a using pre-generated sieve
  2. std::vector<int> getPrimeFactors(int a, const std::vector<int> & primes) {
  3. std::vector<int> f;
  4. for (auto p : primes) {
  5. if (p > a) break;
  6. if (a % p == 0) {
  7. f.push_back(p);
  8. do {
  9. a /= p;
  10. } while (a % p == 0);
  11. }
  12. }
  13. if (a > 1) f.push_back(a);
  14.  
  15. return f;
  16. }
  17.  
  18. // find coprime pairs A_i and B_j
  19. // A_i and B_i <= 1e9
  20. void solution(const std::vector<int> & A, const std::vector<int> & B) {
  21. // generate prime sieve
  22. std::vector<int> primes;
  23. primes.push_back(2);
  24.  
  25. for (int i = 3; i*i <= 1e9; ++i) {
  26. bool isPrime = true;
  27. for (auto p : primes) {
  28. if (i % p == 0) {
  29. isPrime = false;
  30. break;
  31. }
  32. }
  33. if (isPrime) {
  34. primes.push_back(i);
  35. }
  36. }
  37.  
  38. int N = A.size();
  39.  
  40. struct Entry {
  41. int n = 0;
  42. int64_t p = 0;
  43. };
  44.  
  45. // cntp[X] - number of times the product X can be expressed
  46. // with prime factors of A_i
  47. std::map<int64_t, int64_t> cntp;
  48.  
  49. for (int i = 0; i < N; i++) {
  50. auto f = getPrimeFactors(A[i], primes);
  51.  
  52. // count possible products using non-repeating prime factors of A_i
  53. std::vector<Entry> x;
  54. x.push_back({ 0, 1 });
  55.  
  56. for (auto p : f) {
  57. int k = x.size();
  58. for (int i = 0; i < k; ++i) {
  59. int nn = x[i].n + 1;
  60. int64_t pp = x[i].p*p;
  61.  
  62. ++cntp[pp];
  63. x.push_back({ nn, pp });
  64. }
  65. }
  66. }
  67.  
  68. // use Inclusion–exclusion principle to count non-coprime pairs
  69. // and subtract them from the total number of prairs N*N
  70.  
  71. int64_t cnt = N; cnt *= N;
  72.  
  73. for (int i = 0; i < N; i++) {
  74. auto f = getPrimeFactors(B[i], primes);
  75.  
  76. std::vector<Entry> x;
  77. x.push_back({ 0, 1 });
  78.  
  79. for (auto p : f) {
  80. int k = x.size();
  81. for (int i = 0; i < k; ++i) {
  82. int nn = x[i].n + 1;
  83. int64_t pp = x[i].p*p;
  84.  
  85. x.push_back({ nn, pp });
  86.  
  87. if (nn % 2 == 1) {
  88. cnt -= cntp[pp];
  89. } else {
  90. cnt += cntp[pp];
  91. }
  92. }
  93. }
  94. }
  95.  
  96. printf("cnt = %d\n", (int) cnt);
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement