首页 > 解决方案 > 我可以优化埃拉托色尼的分段筛吗

问题描述

我试图在 c++ 中找到给定范围内的素数。但它仍然显示 TLE。我可以进一步优化它吗?

#include <bits/stdc++.h>
using namespace std;

int main() 
{
int T;
std::cin>>T;
while(T--){
    int r,Y;
    cin >> r>>Y;                                  
    int count=0;
    int l=1;
    vector<bool>isPrime(r - l + 1,true); //filled by true
    for (long long i = 2; i * i <= r; ++i) {
        for (long long j = max(i * i, (l + (i - 1)) / i  * i); j <= r; j += i) {
           if(isPrime[j - l]){ 
              isPrime[j - l] = false;
              count++;
        }
    }
} 

count=isPrime.size()-count-1;
std::cout<<count<<"\n";
}  
  return 0;
}

标签: c++counter

解决方案


推荐阅读