fork(1) download
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3.  
  4. #define int int64_t
  5. #define trav(i, a) for(auto& i: a)
  6. #define all(a) a.begin(), a.end()
  7. #define rall(a) a.rbegin(), a.rend()
  8. #define si(a) ((int)(a).size())
  9. #define ins insert
  10. #define pb push_back
  11. #define mp make_pair
  12. #define f first
  13. #define s second
  14.  
  15. const int MOD = 1e9 + 7;
  16. const int INF = 1e18;
  17. const string nl = "\n";
  18. const int N = 1e8;
  19.  
  20. void oldsieve() {
  21. int n = N;
  22. vector<char> is_prime(n+1, true);
  23. is_prime[0] = is_prime[1] = false;
  24. for (int i = 2; i <= n; i++) {
  25. if (is_prime[i] && i * i <= n) {
  26. for (int j = i * i; j <= n; j += i)
  27. is_prime[j] = false;
  28. }
  29. }
  30. }
  31.  
  32. void newsieve(int n = N) {
  33. //int prime[n], is_composite[n + 1];
  34. std::vector <int> prime(n);
  35. vector<bool> is_composite(n + 1, 0);
  36. int cnt = 0;
  37. for (int i = 2; i < n; ++i) {
  38. if(!is_composite[i]) {
  39. prime[cnt++] = i;
  40. }
  41. for (int j = 0; j < cnt && i * prime[j] < n; ++j) {
  42. is_composite[i * prime[j]] = true;
  43. if (i % prime[j] == 0) break;
  44. }
  45. }
  46.  
  47. }
  48.  
  49. void newsieve1(int maxN = N) {
  50. int pc = 0, f[maxN], primes[maxN / 10];
  51. // vector<int> f(maxN), primes(maxN / 10);
  52. for(int i = 2; i < maxN; ++i) {
  53. if(!f[i]) {
  54. primes[pc++] = i, f[i] = i;
  55. }
  56. for(int j = 0; j < pc && 1LL * i * primes[j] < maxN && primes[j] <= f[i]; ++j) {
  57. f[i * primes[j]] = primes[j];
  58. }
  59. }
  60. }
  61.  
  62. int32_t main() {
  63. ios::sync_with_stdio(0);
  64. cin.tie(nullptr);
  65.  
  66. auto t = clock();
  67. oldsieve();
  68. auto t1 = clock();
  69. cout << "oldsieve: " << (1.0 * (t1 - t)) / CLOCKS_PER_SEC << nl;
  70. t = clock();
  71. newsieve1();
  72. t1 = clock();
  73. cout << "newsieve: " << (1.0 * (t1 - t)) / CLOCKS_PER_SEC << nl;
  74. }
  75.  
Success #stdin #stdout 1.14s 100624KB
stdin
Standard input is empty
stdout
oldsieve: 1.1364
newsieve: 0