筛法!!!

C/C++筛选法算素数

什么是求素数

)i在2到n-1之间任取一个数,如果n能被整除则不是素数,否则就是素数

普通枚举法:

#include <iostream>
#include <string>
#include <cmath>
#include <cstring>
using namespace std;

bool isPlain(int x){
    if(x<2) return false;
    else{
        for(int i=2;i<x;i++)
        {
            if(!(x%i))
                return false;
        }
    }
    return true;
}

int main()
{
    int n;
    cin>>n;
    int cot=0;
    for(int j=0;j<n;j++){
        if(isPlain(j)){
           cout<<j<<((++cot%7==0)?"\n":"\t");
        }
    }

}

筛选法:

  • 原始版本:
#include <iostream>
#include <string>
#include <cmath>
#include <cstring>
using namespace std;


int main()
{
    int n;
    cin>>n;
    bool* ans=new bool[n];
    memset(ans,true,sizeof(bool)*n);//
    ans[0]=false;
    ans[1]=false;
    for(int i=2;i<n;i++){
        if(ans[i]){
            for(int j=i*2;j<n;j+=i){//倍数取整
                ans[j]=false;
            }
        }
    }
    int col = 0;
    for(int i=0;i<n;i++){
        if(ans[i]){
            cout<<i<<" ";
        }
    }
    return 0;
}
  • 改进版本
#include <iostream>
#include <string>
#include <cmath>
#include <cstring>
#include <bitset>
using namespace std;

int main()
{
    int n;
    cin>>n;
    bitset<100000> ans;
    ans.set(0);
    ans.set(1);
    for(int j=2; j<=sqrt(n); j++)
    {
        for(int i=2*j; i < n; i+=j)
        {
            ans.set(i);
        }
    }
    int cot=0;
    for(int i=0; i<n; i++)
    {
        if(ans[i]!=1)
        {
            cout<<i<<((++cot%7==0)?"\n":"\t");
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值