埃拉托尼斯筛

#include<cstdio> #include<algorithm> #include<iostream> #include<cstring> using namespace std; const int maxn = 1000010; int pri[10000]; bool a[maxn]; int Eratosthenes_Sieve(int n, int pri[]) { a[0] = a[1] = 1; for (int i = 2; i * i <= n; i++) { if (!a[i]) { for (int j = i << 1; j <= n; j += i) { a[j] = 1; } } } int cnt = 0; for (int i = 2; i <= n; i++) { if (!a[i])pri[cnt++] = i; } return cnt; } //typedef long long ll; int main(void) { long long L, R; scanf("%lld %lld", &L, &R); int cnt = Eratosthenes_Sieve(50000, pri); //cout << cnt; memset(a, 0, sizeof(a)); for (int i = 0; i < cnt; i++) { for (long long j = max(2ll, ((L - 1) / pri[i] + 1)) * pri[i]; j <= R; j += pri[i]) { a[j - L] = 1; } } if (L == 1)a[0] = 1; int ans = 0; for (long long i = L; i <= R; i++) { if (!a[i - L])ans++; } cout << ans; return 0; }
计算机小白记录学习过程,喜欢就点个推荐和关注吧O(∩_∩)O哈哈~

浙公网安备 33010602011771号