Advertisement
Spidey2182

Splitting Bill O(1) per case with Precomputation (C++)

Jul 5th, 2023 (edited)
639
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int* sieveOfEratosthenes(int n) {
  6.     int* sieve = new int[n + 5];
  7.     for (int i = 0; i < n + 5; i++)
  8.         sieve[i] = 1;
  9.     sieve[0] = 0;
  10.     for (int i = 2; i * i < n + 5; i++)
  11.         for (int j = i * i; j < n + 5; j += i)
  12.             sieve[j] = i;
  13.     return sieve;
  14. }
  15.  
  16. int main() {
  17.     int* sieve = sieveOfEratosthenes(1000000);
  18.  
  19.     int testCases;
  20.     cin >> testCases;
  21.     for (int testCase = 1; testCase <= testCases; testCase++) {
  22.         int n;
  23.         cin >> n;
  24.         cout << n / sieve[n] - sieve[n] << '\n';
  25.     }
  26.    
  27.     return 0;
  28. }
  29.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement