Aizu 1172 Chebyshev's Theorem

题目链接:Aizu 1172 Chebyshev's Theorem

求素数,范围比较大,求素数那块要写成i + i,不能是i * i,或者用long long也行。

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>

using namespace std;

const int MAX_N = 2 * 123456 + 100;
bool primes[MAX_N];
int sum[MAX_N];

void init()
{
    memset(primes, false, sizeof(primes));
    primes[0] = primes[1] = 1;
    for(int i = 2; i < MAX_N; i++)
    {
        if(!primes[i])
        {
            for(int j = i + i; j < MAX_N; j += i)
                primes[j] = 1;
        }
    }
    sum[0] = 0;
    for(int i = 1; i < MAX_N; i++)
    {
        sum[i] = sum[i - 1];
        if(!primes[i])
            sum[i]++;
    }
}

int main()
{
    int n;
    init();
    while(scanf("%d", &n), n)
        printf("%d\n", sum[n << 1] - sum[n]);
    return 0;
}


你可能感兴趣的:(Aizu 1172 Chebyshev's Theorem)