PAT B1007 素数对猜想 (20point(s))

让我们定义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
``

### 输出样例:
```out
4
  • 思路:
    求出素数表,遍历到不超过N的素数,判断每相邻的两个素数是否满足素数对猜想,满足cnt++,最后输出素数对

  • code:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int prime[maxn];
bool p[maxn];

void GetPrime(int n){
	int idex = 0;
	for(int i = 2; i < maxn; ++i){
		if(p[i] == false){
			prime[idex++] = i;
			if(i > n) break;
			for(int j = i + i; j < maxn; j += i){
					p[j] = true;
			}
		}
	}
}


int main(){
	int n, cnt = 0;
	scanf("%d", &n);
	GetPrime(n);
	for(int i = 1; prime[i] <= n; ++i){
		if(prime[i] - prime[i-1] == 2){
			cnt++;
		}
	}
	printf("%d", cnt);
	return 0;
}
发布了271 篇原创文章 · 获赞 5 · 访问量 6527

猜你喜欢

转载自blog.csdn.net/qq_42347617/article/details/104093733