POJ-2689-Prime Distance

ACM模版

题目链接

POJ 2689 Prime Distance

题解

素数排查问题,问题的关键在于如何找出给定区间中的所有素数,涉及到一个预处理。

代码

#include 

using namespace std;

const int MAXN = 100010;
int prime[MAXN + 1];

//  预处理
void getPrime()
{
    memset(prime, 0, sizeof(prime));
    for (int i = 2; i <= MAXN; i++)
    {
        if (!prime[i])
        {
            prime[++prime[0]] = i;
        }
        for (int j = 1; j <= prime[0] && prime[j] <= MAXN / i; j++)
        {
            prime[prime[j] * i] = 1;
            if (i % prime[j] == 0)
            {
                break;
            }
        }
    }
}

bool notPrime[1000010];
int primes[1000010];

void getPrimes(int L, int R)
{
    memset(notPrime, false, sizeof(notPrime));
    if (L < 2)
    {
        L = 2;
    }
    for (int i = 1; i <= prime[0] && (long long)prime[i] * prime[i] <= R; i++)
    {
        int s = L / prime[i] + (L % prime[i] > 0);
        if (s == 1)
        {
            s = 2;
        }
        for (int j = s; (long long)j * prime[i] <= R; j++)
        {
            if ((long long)j * prime[i] >= L)
            {
                notPrime[j * prime[i] - L] = true;
            }
        }
    }
    primes[0] = 0;
    for (int i = 0; i <= R - L; i++)
    {
        if (!notPrime[i])
        {
            primes[++primes[0]] = i + L;
        }
    }
}

int main(int argc, const char * argv[])
{
    //  预处理
    getPrime();
    int L, U;
    while (cin >> L >> U)
    {
        getPrimes(L, U);
        if (primes[0] < 2)    //  素数数量不够成对
        {
            cout << "There are no adjacent primes.\n";
        }
        else
        {
            int xOne = 0, xTwo = 100000000, yOne = 0, yTwo = 0;
            for (int i = 1; i < primes[0]; i++)
            {
                if (primes[i + 1] - primes[i] < xTwo - xOne)    //  排查最近的素数对
                {
                    xOne = primes[i];
                    xTwo = primes[i + 1];
                }
                if (primes[i + 1] - primes[i] > yTwo - yOne)    //  排查最远的素数对
                {
                    yOne = primes[i];
                    yTwo = primes[i + 1];
                }
            }
            cout << xOne << ',' << xTwo << "are closest," << yOne << ',' << yTwo << "are most distant.\n";
        }
    }

    return 0;
}

你可能感兴趣的:(ACM模版篇,数论,素数)