sgu 231. Prime Sum 素數篩選


231. Prime Sum

time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard



Find all pairs of prime numbers (A, B) such that A<=B and their sum is also a prime number and does not exceed N.

Input
The input of the problem consists of the only integer N (1<=N<=10^6).

Output
On the first line of the output file write the number of pairs meeting the requirements. Then output all pairs one per line (two primes separated by a space).

Sample test(s)

Input
4
Output
0



素數只有2是偶數,其他兩奇數之和爲偶數不是素數,所以就是求素數差爲2的素數對數量。


#include <bits/stdc++.h>

using namespace std;

bool v[1000005];

void solve(){
    int n;
    scanf("%d",&n);
    for(int i=2;i*i<=n;i++){
        if(v[i]==1)continue;
        for(int j=2*i;j<=n;j+=i){
            v[j]=1;
        }
    }

    int ans=0;
    for(int i=5;i<=n;i++){
        if(v[i]==0&&v[i-2]==0){
            ans++;
        }
    }
    printf("%d\n",ans);
    for(int i=5;i<=n;i++){
        if(v[i]==0&&v[i-2]==0){
            printf("%d %d\n",2,i-2);
        }
    }

}

int main(){
    solve();
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章