自测-2 素数对猜想(20 分)
让我们定义dn为:dn=pn+1−pn,其中pi是第i个素数。显然有d1=1,且对于n>1有dn是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。
现给定任意正整数N
(<105),请计算不超过N
的满足猜想的素数对的个数。
输入格式:
输入在一行给出正整数N
。
输出格式:
在一行中输出不超过N
的满足猜想的素数对的个数。
输入样例:
20
输出样例:
4
题目源于:https://pintia.cn/problem-sets/17/problems/261
思路分析:根据题意 " 现给定任意正整数N(<10^5 ),请计算不超过N的满足猜想的素数对的个数。" 建立一个10的5次方大小的bool型数组points,算法思路重点!!!从0开始访问遇到的第一个素数:2(注:0和1不是素数也不是合数)将所有偶数(即2的倍数)下标写为假,2写为真,寻找一下个质数X,将X之后所有的倍数(即2X,3X.....nX<=10^5)全置为假,将X写为真,以此类推遍历整个数组,而后所有值为真的下标即为素数,再判断相邻素数只差,来求解素数对。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
bool points[100000] = {0};
void primer(int N, bool * a);
bool isPrimer(int n);
int main()
{
int N;
cin >> N;
points[2] = true;
// for (int i = 4; i <= N; i += 2) points[i] = false; //将偶数全置为假,即认为是合数
for (int i = 3; i <= N; i += 2)points[i] = true; //尚未判断的数字全写为真
primer(N, points);
vector<int> a;
for (int i = 2; i <= N; i++) {
if (points[i]) a.push_back(i);
}
int count=0;
int length = a.size();
for (int i = 0; i < length-1; i++) {
if (a[i + 1] - a[i] == 2) count++;
}
cout << count;
return 0;
}
void primer(int N, bool * a) {
int i = 3;
//素数为true!合数为false
while (i <= N ) {
if (a[i]&&isPrimer(i)) { //当数字i没有做过判断,并且为素数时,进行以下操作
//首先将points i写为真,即认为i是素数
for (int j = 2 * i; j < N; j += i) a[j] = false;//将i的倍数全写为合数
}
i++;
}
}
//判断N是否为素数
bool isPrimer(int n) {
int sqr = sqrt(n);
for(int i = 3; i <= sqr; i++) {
if (n%i == 0) return false;
}
return true;
}
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
bool points[100000] = {0};
void primer(int N, bool * a);
bool isPrimer(int n);
int main()
{
int N;
cin >> N;
points[2] = true;
// for (int i = 4; i <= N; i += 2) points[i] = false; //将偶数全置为假,即认为是合数
for (int i = 3; i <= N; i += 2)points[i] = true; //尚未判断的数字全写为真
primer(N, points);
vector<int> a;
for (int i = 2; i <= N; i++) {
if (points[i]) a.push_back(i);
}
int count=0;
int length = a.size();
for (int i = 0; i < length-1; i++) {
if (a[i + 1] - a[i] == 2) count++;
}
cout << count;
return 0;
}
void primer(int N, bool * a) {
int i = 3;
//素数为true!合数为false
while (i <= N ) {
if (a[i]&&isPrimer(i)) { //当数字i没有做过判断,并且为素数时,进行以下操作
//首先将points i写为真,即认为i是素数
for (int j = 2 * i; j < N; j += i) a[j] = false;//将i的倍数全写为合数
}
i++;
}
}
//判断N是否为素数
bool isPrimer(int n) {
int sqr = sqrt(n);
for(int i = 3; i <= sqr; i++) {
if (n%i == 0) return false;
}
return true;
}