Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现
来源:互联网 发布:集搜客网页抓取软件 编辑:程序博客网 时间:2024/05/24 07:19
埃拉托色尼筛选法
埃拉托色尼选筛法(the Sieve of Eratosthenes)简称埃氏筛法,是古希腊数学家埃拉托色尼(Eratosthenes 274B.C.~194B.C.)提出的一种筛选法。 是针对自然数列中的自然数而实施的,用于求一定范围内的质数。步骤
(1)先把1删除(现今数学界1既不是质数也不是合数)(2)读取队列中当前最小的数2,然后把2的倍数删去
(3)读取队列中当前最小的数3,然后把3的倍数删去
(4)读取队列中当前最小的数5,然后把5的倍数删去
(5)如上所述直到需求的范围内所有的数均删除或读取
示例
Apply sieve of Eratosthenes to find all primes in range 2..100.
Initial grid
2 is prime, mark all multiples of 2, starting from 4
3 is prime, mark all multiples of 3, starting from 9
5 is prime, mark all multiples of 5, starting from 25
7 is prime, mark all multiples of 7, starting from 49
112 is more, than 100, all unmarked numbers are primes
Final result
代码
public class Prime_Sieve {private boolean[] sieveOfEratothenes(int max) {boolean[] flags = new boolean[max + 1];// int count = 0;for (int i = 2; i < flags.length; i++) {flags[i] = true;}int prime = 2;while (prime <= max) {// 划掉余下prime倍数的数字crossOff(flags, prime);// 找出下一个为true的值prime = getNextPrime(flags, prime);if (prime >= flags.length) {break;}}return flags;}private void crossOff(boolean[] flags, int prime) {// 划掉余下为prime倍数的数字// 我们可以从prime*prime开始// 因为如果k*prime且k<prime,这个值早就在迭代之前就被划掉了for (int i = prime * prime; i < flags.length; i = i + prime) {flags[i] = false;}}private int getNextPrime(boolean[] flags, int prime) {int next = prime + 1;while (next < flags.length && flags[next] == false) {next++;}return next;}public static void main(String[] args) {Prime_Sieve myPrime_Sieve = new Prime_Sieve();boolean[] mySieveArray = myPrime_Sieve.sieveOfEratothenes(16);for (int i = 0; i <= 16; i++) {System.out.println(i + " is prime: " + mySieveArray[i]);}}}
优化
当然上面的代码中,还有一些地方可以优化,比如只将奇数放入数组所需空间即可减半。
1 0
- Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现
- 素数筛法【Sieve Of Eratosthenes + Sieve Of Euler】
- Sieve Of Eratosthenes求素数(埃拉托斯特尼筛法)
- Sieve of Eratosthenes Algorithm算法 JAVA实现
- 找质数算法之埃拉托色尼筛选法(Sieve of Eratosthenes算法)
- Sieve of Eratosthenes算法实现
- 素数筛法/埃拉托斯特尼筛法(sieve of Eratosthenes)——理解及具体问题
- 埃拉托斯特尼筛法(Sieve of Eratosthenes)简单c实现
- 了解BitSet类并实现素数筛选--Eratosthenes筛选法
- Sieve of Eratosthenes(埃拉托斯尼斯筛法)
- Sieve of Eratosthenes[ZT]
- The Sieve of Eratosthenes
- Sieve of Eratosthenes
- sieve of Eratosthenes 找质素
- the Sieve of Eratosthenes
- 09 Sieve of Eratosthenes
- Sieve of Eratosthenes
- sieve of Eratosthenes——一种寻找素数的方法
- SQL快速参考list
- linux下安装nginx
- Java的ArrayList与Vector比较
- Spring Boot示例 - 1. 使用Spring Boot Actuator构建RESTful web service
- CentOS7 常用命令总结
- Sieve of Eratosthenes(埃拉托斯特尼素数筛选法)--java实现
- CentOS7 PHP 连接 MSSQL 2008
- 他成就比李安还高,却半辈子活在歧视中
- iOS给照片添加水印效果
- python机器学习sklearn数据集iris介绍
- MySQL数据库迁移
- 可能是目前最详细的游戏运维指南
- HDU 1166 一维树状数组
- Spring配置文件中读取properties文件的属性