zoukankan      html  css  js  c++  java
  • PAT B1007 素数对猜想 (20 分)

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

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

    输入格式:

    输入在一行给出正整数N

    输出格式:

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

    输入样例:

    20
    

    输出样例:

    4
    #include <stdio.h>
    #include <algorithm>
    #include <string>
    #include <map>
    #include <iostream>
    #include <stack>
    #include <math.h>
    using namespace std;
    const int maxn = 100010;
    int index[maxn] = { 0 };
    bool isPrime(int i){
        for (int k = 2; k <= sqrt(i); k++){
            if (i%k == 0)return false;
        }
        return true;
    }
    int main(){
        int n, count = 0;
        cin >> n;
        if (n == 1 || n == 2){
            cout << '0';
            return 0;
        }
        for (int i = 2; i <= n; i++){
            if (isPrime(i)){
                index[i] = 1;
                
            }
        }
        for (int i = 2; i <= n-2; i++){
            if(index[i]==1 && (index[i + 2] - index[i] == 0))count++;
        }
        cout << count;
        system("pause");
    }

    注意点:素数的判定一直是一个重点,本以为判断到平方根也会超时,结果没有还算好,有时间要去看一下时间复杂度最低的素数判定方法。这里我是把所有素数都存起来,用了hash,也可以生成一个判断一个,可以省点内存。

    ---------------- 坚持每天学习一点点
  • 相关阅读:
    ZOJ
    CodeForces
    模板
    前门
    错误记录
    2021/1/10例会 academy of management journal 2014vol 57 No.2,484-514
    Day7下
    Day7上
    Day6 下(
    Day6上 括号匹配专项
  • 原文地址:https://www.cnblogs.com/tccbj/p/10359177.html
Copyright © 2011-2022 走看看