埃拉托斯特尼(Eratosthene)筛法
来源:互联网 发布:广州做网络推广的公司 编辑:程序博客网 时间:2024/06/06 02:20
下面是代码:
/* 功能:将1-n的素数输出
使用了埃拉托斯特尼(Eratosthene)筛法
*/
#include <iostream>
#include <math.h>
using namespace std;
int prime[10000000];//存放需要筛选数
int sieve (int *prime,int n,int k)//n是1-n这个范围,k是当前把prime[k]作为筛子
{
for (int i= k+1; i<=n ; i++)
{
//当前数prime[i]不为0且能整出筛子数,说明肯定是合数
if (prime[i] && prime[i]%prime[k]== 0)
{
prime[i] = 0;//将合数赋值为0
}
}
k++;
//如果当前筛子数是0,则移到下一位
while (!prime[k])
{
k++;
}
return k;
}
int main()
{
int n;
while (cin >> n && n)
{
int k = 2;//从素数2开始
for (int i = 1; i <= n; i++)
{
prime[i] = i;
}
while (prime[k]<= sqrt(n))
{
k = sieve(prime,n,k);//找到下一个筛子
}
for (int i = 2; i<= n; i++)
{
if (prime[i]!= 0)
{
cout << prime[i] <<" ";
}
}
}
return 0;
}
当然,这是一个非常初级的版本,如果你想找出你给定数组的素数,只要稍微改正即可。
- 埃拉托斯特尼(Eratosthene)筛法
- 筛法
- 筛法
- 筛法
- 筛法
- 筛法
- 埃拉托斯特尼筛选法
- 埃拉托斯特尼素数筛法
- 筛法,埃氏筛法 Eular筛法
- 埃拉托斯特尼 之 超出范围100000000
- Eratosthenes筛法
- POJ3292 筛法
- Eratosthenes筛法
- Eratosthenes筛法
- Eratosthenes筛法
- Eratosthenes筛法
- 【1453】筛法
- 筛法2
- 开机加载内核前的原理(硬件启动)
- Erlang入门:构建application练习2
- 未解决问题
- Cocos2dx 3.0 过渡篇(八)浅谈容器Vector
- pt-query-digest查询日志分析工具
- 埃拉托斯特尼(Eratosthene)筛法
- LeetCode OJ 之 Rotate List (链表旋转)
- ubuntu 安装libpostproc52出错。
- 爱干货:Google Play开发者账号注册 最新攻略【2014-01-13】
- Android-小小设置永久解决程序因为未捕获异常而异常终止的问题
- windows inet_ntop inet_pton可参考linux下的实现
- Linux进程间通信——使用信号量
- hashmap简单实例(个人使用经验)
- 单例模式(Singletond)