素数对猜想 PAT

让我们定义d​n​​为:d​n​​=p​n+1​​−p​n​​,其中p​i​​是第i个素数。显然有d​1​​=1,且对于n>1有d​n​​是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<10​5​​),请计算不超过N的满足猜想的素数对的个数。

#include<iostream>
using namespace std;

void main() {
    int n, ad = 0, b[100] = { 0 },j=0;
    bool a[100] = { false };//首先把所有的数字定义为不是合数
    cin >> n;//输入要验证的数字

    a[1] = a[0] = true;//0和1都不是素数也不是合数

    if (n == 0 || n == 1) cout<<"0";//如果输入的数字为0或1,直接输出错误值
    else {
        for (int i = 2; i <= n ; i++) {//当数字不是合数(也就是素数)时进入循环。
            if (a[i] == true)//已经判断过不是素数的数
                continue;
            for (int j = i*i; j <= n; j += i)
                a[j] = true;//将最小的素数的倍数都定义为是合数
        }
    }

    for (int i = 2; i <= n; i++) {
        if (a[i] == false) {
            b[j] = i;
            j++;
        }//将a数组里为素数的值按顺序放在b数组中
    }

    for (int i = 0; i < j - 1; i++){
        if (b[i + 1] - b[i] == 2) 
            ad++;
    }//判断后面的数减去前面的是否为2

    if (n != 0 && n != 1)
        cout << ad;
}

猜你喜欢

转载自blog.csdn.net/qq_42082542/article/details/83686177