Linear sieve

twin prime problem

Time Limit: 3000  ms | Memory Limit: 65535  KB
Difficulty: 3
describe
Write a program that finds the number of groups that give all twin primes in the range of primes. Generally speaking, a twin prime number refers to two prime numbers whose distance is 2, and the closest prime numbers cannot be closer. Some children's shoes start to write programs as soon as they see the question, and they don't read the question carefully. In order to curb the children's shoes who do not read the question carefully, it is stipulated that two prime numbers adjacent to 1 also become twin prime numbers.
enter
The first line gives N (0<N<100) indicating the number of test data sets.
The next set of test data gives m, which means to find all the twin primes before m.
(0<m<1000000)
output
Each set of test data output occupies one line, which is the number of all twin prime arrays within the range of m.
sample input
1
14
Sample output
4
source
[hzyqazasdf] Original
Uploaded by
hzyqazasdf



#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#define INF 0x3f3f3f3f
#define MOD 1000000000+7
using namespace std;
const int maxn = 1000000+10;
bool f[maxn];
long long p[maxn],k;
void check()
{
    f[0]=1;
    f[1]=1;
    for(int i=2; i<=maxn; i++)
    {
        if(!f[i])
            p[k++]=i;
        for(int j=0; p[j]*i<=maxn&&j<k; j++)
        {
            f[p[j]*i]=1;
            if(!(i%p[j]))
                break;
        }
    }
}
int main()
{
    check();
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int cnt=0;
        for(int i=2; i<=n; i++)
        {
            if(f[i]!=1&&f[i-1]!=1) cnt++;
            if(f[i]!=1&&f[i-2]!=1) cnt++;
        }
        cout<<cnt<<endl;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326318686&siteId=291194637