PAT (Basic Level) Practice (中文) 1007 素數對猜想 (20 分) (C++)
阿新 • • 發佈:2019-01-02
1007 素數對猜想 (20 分)
讓我們定義dn為:dn=pn+1 −pn,其中pi是第i個素數。顯然有d1=1,且對於n>1有dn 是偶數。“素數對猜想”認為“存在無窮多對相鄰且差為2的素數”。
現給定任意正整數N(<105 ),請計算不超過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;
}