原博文http://www.cnblogs.com/nowandforever/p/4515612.html
/************************************************ * Author :Powatr * Created Time :2015-8-17 8:56:45 * File Name :区间筛法.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int MAXN = 1e5 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; bool is_prime_small[MAXN]; bool is_prime[MAXN]; ll prime[MAXN]; ll cout1; void segment_sieve (ll a, ll b) { for(ll i = 0 ; i*i < b; i++) is_prime_small[i] = true; for(ll i = 0 ; i < b - a; i++) is_prime[i] = true; for(ll i = 2; i*i < b; i++){ if(is_prime_small[i]){ for(ll j = 2*i; j *j < b; j+=i) is_prime_small[j] = false; for(ll j = max(1ll*2, (a+i-1)/i*i); j < b; j+=i) is_prime[j-a] = false; } } for(ll i = 0; i < b - a; i++){ if(is_prime[i]) prime[++cout1] = i+a; } } int main(){ ll a, b; while(~scanf("%I64d%I64d", &a, &b)){ cout1 = 0; memset(prime, 0, sizeof(prime)); segment_sieve(a, b); printf("%I64d\n", cout1); } return 0; }
时间: 2024-11-05 11:54:00