PAT basic 1007 素数对猜想 (20分) C++

PAT basic 1007 素数对猜想 (20分) C++

一、题目描述

让我们定义d​n为:d​n=p​n+1−p​n​​ ,其中p​i​​ 是第i个素数。显然有d
​1=1,且对于n>1有d​n 是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。现给定任意正整数N(<100000​ ),请计算不超过N的满足猜想的素数对的个数。

输入格式:
输入在一行给出正整数N。

输出格式:
在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:
20

输出样例:
4

二、代码

#include<stdlib.h>
#include<math.h>
#include<iostream>
using namespace std;

int main()
{
	int n,temp1,temp2=2,flag,count=0;
	cin >> n;
	for (int i = 3; i <= n; i++)
	{
		flag = 1;
		for (int j = 2; j <= sqrt(i); j++)
		{
			if (i%j == 0)
			{
				flag = 0;
				break;
			}

		}
		if (flag == 1)
		{
			temp1 = temp2;
			temp2 = i;
			if (temp2 - temp1 == 2)
				count++;
		}
	}
	cout << count;


	system("pause");
	return 0;
}

三、运行结果

在这里插入图片描述

四、题目合集

点这里~

发布了42 篇原创文章 · 获赞 0 · 访问量 778

猜你喜欢

转载自blog.csdn.net/qq_44352065/article/details/103773138