1007 素數對猜想 (20 分)
讓我們定義dn爲:dn=pn+1−pn,其中pi是第i個素數。顯然有d1=1,且對於n>1有dn是偶數。“素數對猜想”認爲“存在無窮多對相鄰且差爲2的素數”。
現給定任意正整數N
(<105),請計算不超過N
的滿足猜想的素數對的個數。
輸入格式:
輸入在一行給出正整數N
。
輸出格式:
在一行中輸出不超過N
的滿足猜想的素數對的個數。
輸入樣例:
20
輸出樣例:
4
題記:
C++程序如下:
#include <iostream>
#include <cmath>
using namespace std;
const int N = 100000;
int p[N];
bool isprime(int n){
if(n % 2 == 0){
return 0;
}
int end = sqrt(n), i;
for(int i=3; i<=end; i+=2) {
if(n % i == 0){
return 0;
}
}
return 1;
} //判斷素數函數
int main(void){
int n, count=0, p1=2, p2;
cin >> n;
for(int i=3; i<=n; i++){
if(isprime(i)){
p2 = i;
if(p2 - p1 == 2){
count ++;
}
p1 = p2;
}
}
cout << count;
return 0;
}