当前位置:网站首页>线性筛法(素数筛)
线性筛法(素数筛)
2022-04-22 05:35:00 【Ice Cream~】
一个O(n)时间复杂度的筛选质数的算法:
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
const int N=1000000;
int primes[N],cnt;//primes数组存放质数
int minp[N];//存放最小质因子
bool st[N];//当前有没有被筛选
void get_primes(int n)
{
for(int i=2;i<=n;i++)
{
if(!st[i])minp[i]=i,primes[cnt++]=i;
for(int j=0;primes[j]*i<=n;j++)//筛选质数
{
st[primes[j]*i]=true;
minp[primes[j]*i]=primes[j];//primes[j]*i的最小质因子是priems
if(i%primes[j]==0)break;//primes不大于i的最小质因子
}
}
}
int main()
{
get_primes(10000);
for(int i=2;i<20;i++)
{
cout<<primes[i]<<" "<<minp[i]<<endl;
}
}
版权声明
本文为[Ice Cream~]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_52797843/article/details/122611769
边栏推荐
- Redis real-time synchronization tool recommendation
- C language version: establishment and basic operation of circular queue
- 2.words平均长度
- Strong connected component of "tarjan" undirected graph
- 力扣19. 删除链表的倒数第 N 个结点
- MySQL JDBC programming
- Using easyexcel to export excel forms
- POI 和 EasyExcel练习
- MySQL表的增删改查
- 二叉树五个重要性质(附图理解)
猜你喜欢

Fundamentals of Unreal Engine Programming (II)

Kaggle_NBME NLP比赛Baseline详解(2)

Using easyexcel to export excel forms

MySQL数据库基础

JUC concurrent programming

C language version: binary tree leaf node and non leaf node solution

JVM探究

Domain based approach - score prediction

I/O基础知识入门

C language version: establishment and basic operation of chain team
随机推荐
MySQL高级查询
数据已删除,又重新出现的问题排查
Redis real-time synchronization tool recommendation
Domain based approach - score prediction
Enquête JVM
Fundamentals of Unreal Engine Programming (II)
Integer source code
mysql非常用命令
GBase 8s V8. 8 SQL Guide: tutorial-5.2 (3)
C language practice (2) -- polynomial addition with linked list
Homebrew的基本使用与常见异常
GBase 8s V8. 8 SQL Guide: tutorial-5.3
General compilation methods of third-party libraries such as libcurl
认识和安装MySQL
可重入锁线程等待唤醒示例
GBase 8s V8. 8 SQL Guide: tutorial-5.4
C語言練習(2)——鏈錶實現多項式加法
Spark 之 unsafeRow
After unity is connected to the ilruntime, the package method under packages is applied to the hot engineering application, such as unity RenderPipelines. Core. Runtime package
稳定性建设最佳实践