zoukankan      html  css  js  c++  java
  • 素数

    觉得还是总结一下为好
    这里涉及到直接判断和筛法(PS:黑书上看到一个更优的方法,但并不太会,等会了以后尽量补上)

    利用定义直接判断:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    int n;
    int i,j;
    bool f=false;
    
    bool pd(int x)
    {
        if (x==2) return true;
        for (j=2;j<=trunc(sqrt(x));j++)
            if (x%j==0)
                return false;
        return true;
    }
    
    int main()
    {
        scanf("%d",&n);
        for (i=2;i<=n-2;i++)
            if (pd(i) && pd(i+2))
                {
                    printf("%d %d
    ",i,i+2);
                    f=true;
                }
        if (f!=true)
            printf("empty");
      return 0;
    }

    素数的筛法:

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    bool pd[10001]={false};
    int prime[5000]={0};
    int i,j;
    int zz=0;
    int n;
    bool f=false;
    
    int main()
    {
        scanf("%d",&n);
        for (i=2;i<=n;i++)
            {
                if (pd[i]==false)
                    prime[++zz]=i;
                    for (j=i;j<=n/i;j++)
                        pd[i*j]=true;
            }
        for (i=1;i<=zz-1;i++)
            if (prime[i]+2==prime[i+1])
                {
                    printf("%d %d
    ",prime[i],prime[i+1]);
                    f=true;
                }
        if (f!=true)
            printf("empty");
      return 0;
    }

    PS:上题转自NOI题库-素数对http://noi.openjudge.cn/ch0112/10/

    ——It's a lonely path. Don't make it any lonelier than it has to be.
  • 相关阅读:
    JavaScript Date对象
    BOM 和 DOM
    JS变量声明方式
    CSS3 选择器
    Python文件操作
    第十三章 迭代器、生成器、 装饰器
    python专题 --- 递归
    React JSX
    ES6——面向对象应用
    ES6——面向对象-基础
  • 原文地址:https://www.cnblogs.com/DaD3zZ-Beyonder/p/5346267.html
Copyright © 2011-2022 走看看