1 Star 0 Fork 3

aiobc/Algorithms

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
SieveOfEratosthenes.java 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
Rafael Chaves 提交于 2020-02-03 02:07 +08:00 . Adopt standard Java project layout (#120)
/**
* Use the sieve of eratosthenes to find all the prime numbers up to a certain limit.
*
* <p>Time Complexity: O(nloglogn)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
package com.williamfiset.algorithms.math;
public class SieveOfEratosthenes {
// Gets all primes up to, but NOT including limit (returned as a list of primes)
public static int[] sieve(int limit) {
if (limit <= 2) return new int[0];
// Find an upper bound on the number of prime numbers up to our limit.
// https://en.wikipedia.org/wiki/Prime-counting_function#Inequalities
final int numPrimes = (int) (1.25506 * limit / Math.log((double) limit));
int[] primes = new int[numPrimes];
int index = 0;
boolean[] isComposite = new boolean[limit];
final int sqrtLimit = (int) Math.sqrt(limit);
for (int i = 2; i <= sqrtLimit; i++) {
if (!isComposite[i]) {
primes[index++] = i;
for (int j = i * i; j < limit; j += i) isComposite[j] = true;
}
}
for (int i = sqrtLimit + 1; i < limit; i++) if (!isComposite[i]) primes[index++] = i;
return java.util.Arrays.copyOf(primes, index);
}
public static void main(String[] args) {
// Generate all the primes up to 29 not inclusive
int[] primes = sieve(29);
// Prints [2, 3, 5, 7, 11, 13, 17, 19, 23]
System.out.println(java.util.Arrays.toString(primes));
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/aiobc/Algorithms.git
git@gitee.com:aiobc/Algorithms.git
aiobc
Algorithms
Algorithms
master

搜索帮助