LightOJ 1197 Help Hanzo 求区间内素数的个数

来源:互联网 发布:手机和mac照片同步 编辑:程序博客网 时间:2024/05/22 06:56
  1. 数论题尽量都用longlong。
  2. 先打出小部分素数,用这部分素数筛区间内的素数。

题目链接:http://acm.hust.edu.cn/vjudge/problem/26909

#include<cstdio>#include<iostream>#include<sstream>#include<cstdlib>#include<cmath>#include<cctype>#include<string>#include<cstring>#include<algorithm>#include<stack>#include<queue>#include<set>#include<map>#include<ctime>#include<vector>#include<fstream>#include<list>using namespace std;#define ms(s) memset(s,0,sizeof(s))typedef unsigned long long ULL;typedef long long LL;const int INF = 0x3fffffff;bool isPrime[100005];const int N = 1000000;bool primeTable[N+5];int p[N/10],tot;void make_primeTable(){    tot = 0;    fill(primeTable,primeTable+N,1);    primeTable[0] = false;    primeTable[1] = false;    int maxed = sqrt(N);    for(int i = 2; i <= maxed; ++i){        if(primeTable[i] == true){            p[tot++] = i;            for(int j = i*i; j <= N; j += i)                primeTable[j] = false;        }    }    for(int i = maxed+1; i <= N; ++i)        if(primeTable[i] == true)  p[tot++] = i;}int main(){//    freopen("F:\\input.txt","r",stdin);//    freopen("F:\\output.txt","w",stdout);//    ios::sync_with_stdio(false);    LL a,b;    int t;    LL idx;    int ans;    scanf("%d",&t);    make_primeTable();    for(int cas = 1; cas <= t; ++cas){        scanf("%lld%lld",&a,&b);        ms(isPrime);        ans = 0;        int maxs = sqrt(b);        for(int i = 0; i < tot; ++i){            if(p[i] > maxs)                break;            if(a%p[i] == 0)                idx = a;            else                idx = p[i]*(a/p[i]+1);            while(idx <= b){                isPrime[idx-a] = true;                if(idx <= 1000000 && primeTable[idx]==true)                    isPrime[idx-a] = false;                idx += p[i];            }        }        for(int i = 0; i <= b-a; ++i){            if(isPrime[i]==0)                ans++;        }        if(a == 1){            ans--;        }        printf("Case %d: %d\n",cas,ans);    }    return 0;}
1 0
原创粉丝点击