素数筛选法-Eratosthenes筛法优化
来源:互联网 发布:造梦西游4修改器mac版 编辑:程序博客网 时间:2024/06/07 22:42
上一篇文章中提到了Eratosthenes筛法,我们知道Eratosthenes筛法的时间复杂度为nlogn,但是仍然可以优化。
先介绍一下素数定理,即在不超过x的正整数内,素数的个数约为x/lnx个。
代码如下:
#include <stdio.h>
#include <math.h>#define MAX 100
int a[MAX+1];//n的范围
int prime[MAX+1];//素数表
int main()
{
int k=0;
prime[k]=2;//放入第一个素数
//除2以外的素数,都为奇数
for(int i=3;i<=MAX;i+=2)a[i]=0;
//从3开始筛选,根据素数定理,故只用筛到sqrt(n+0.5)即可
for(int i=3;i<=sqrt(MAX+0.5);i+=2)if(a[i]==0)
//除2之外的偶数均以筛过,故可直接从i*i开始筛,j每次循环加2*i,保持j是奇数
for(int j=i*i;j<=MAX;j+=i*2)a[j]=1;
//把素数放进素数表
for(int i=3;i<=MAX;i+=2)if(a[i]==0)
prime[++k]=i;
//输出素数表
for(int i=0;i<=k;i++)printf("%d ",prime[i]);
printf("\n");
return 0;
}
0 0
- 素数筛选法-Eratosthenes筛法优化
- Eratosthenes筛选法求素数的算法
- Eratosthenes筛选法求素数的算法
- 找素数的Eratosthenes算法(筛选法)
- 了解BitSet类并实现素数筛选--Eratosthenes筛选法
- Eratosthenes筛选法
- Eratosthenes筛选法
- Eratosthenes筛选法
- Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现
- Eratosthenes筛选法求小于N的所有素数个数
- 使用埃拉托色尼筛选法(Eratosthenes)得到素数
- Eratosthenes 筛选素数
- Eratosthenes素数筛选
- Eratosthenes求素数法
- Eratosthenes筛选法计算质数
- Eratosthenes筛法生成素数表
- Eratosthenes筛法(素数筛法)
- 学习笔记——求解素数问题之Eratosthenes(埃拉托色尼)筛选法
- 关于链接标签的学习
- 前言
- 浅谈Java中的equals和==
- 如何学好图像处理——从小白到大神?
- [leetcode 250]Count Univalue Subtrees ------元素都相同的子树个数
- 素数筛选法-Eratosthenes筛法优化
- 搜索区间
- c++primer(第五版) 第十三章 拷贝控制习题答案
- 使用基于ThinkPHP3.2.3的ThinkAdmin创建手机电脑通用的表白墙(八)移动端index
- poj 1769 Minimizing maximizer 线段树
- IOS:使用jenkins实现xcode自动打包
- Activity的四种启动模式和onNewIntent()
- Java NIO和IO的区别
- laravel 学习笔记一 (异常处理)