讓我們定義dn 為:dn=pn+1−pn,其中pi 是第i個素數。顯然有d1=1,且對於n>1有dn 是偶數。“素數對猜想”認為“存在無窮多對相鄰且差為2的素數”。
現給定任意正整數N(<10^5 ),請計算不超過N的滿足猜想的素數對的個數。
輸入格式:
輸入在一行給出正整數N。
輸出格式:
在一行中輸出不超過N的滿足猜想的素數對的個數。
輸入樣例:
20
輸出樣例:
4
思路:
每算出1個素數,和前一個素數作差並判定
代碼:
#include <stdio.h>
#include <math.h>//調用函數sqrt(),計算一個非負實數的平方根.
int main(){
int n;
scanf("%d",&n);
int i,j,cnt=0;
int pre=2;
for(i=3;i<=n;i++){//從第二個素數開始遍歷
for(j=2;j<=(int)sqrt((float)i);j++)
if(i%j==0)//判斷不是素數
break;
if(j>sqrt(i)){
if(i-pre==2)//相鄰素數相差2
cnt++;//計數
pre=i;//素數替換
}
}
printf("%d",cnt);
return 0;
}