1007 素數對猜想 (20 分)
讓我們定義d
n
爲:d
n
=p
n+1
−p
n
,其中p
i
是第i個素數。顯然有d
1
=1,且對於n>1有d
n
是偶數。“素數對猜想”認爲“存在無窮多對相鄰且差爲2的素數”。
現給定任意正整數N(<10
5
),請計算不超過N的滿足猜想的素數對的個數。
輸入格式:
輸入在一行給出正整數N。
輸出格式:
在一行中輸出不超過N的滿足猜想的素數對的個數。
輸入樣例:
20
輸出樣例:
4
#include <cstdio>
#include <cstring>
#include <cmath>//使用sqrt函數,需添加math庫
int main()
{
int n = 0;
scanf("%d", &n);
int cnt = 0, last = 2;
for (int i = 3; i <= n; i += 2)
{
int flag = 0;
for (int j = 3; j <= (int)sqrt((double)i); j+=2)//判斷i是否是質數,只需判斷能否被根下i以內的數整除即可
{
if (i%j == 0)
{
flag = 1;
break;
}
}
if (!flag)//是質數
{
if(i - last == 2 ) cnt++;//與上一個質數差爲2則計數
last = i;
}
}
printf("%d", cnt);
return 0;
}