231. Prime Sum
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
memory limit per test: 4096 KB
input: standard
output: 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;
}