版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37454852/article/details/85341223
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;
}