/**
* This class Generates prime numbers up to a user specified
* maximum. The algorithm used is the Sieve of Eratosthenes.
* <p>
* Eratosthenes of Cyrene, b. c. 276 BC, Cyrene, Libya --
* d. c. 194, Alexandria. The first man to calculate the
* circumference of the Earth. Also known for working on
* calendars with leap years and ran the library at Alexandria.
* <p>
* The algorithm is quite simple. Given an array of integers
* starting at 2. Cross out all multiples of 2. Find the next
* uncrossed integer, and cross out all of its multiples.
* Repeat untilyou have passed the square root of the maximum
* value.
*
* @author Alphonse
* @version 13 Feb 2002 atp
*/
import java.util.Arrays;
public class PrimeGenerator {
private static boolean[] crossedOut;
private static int[] result;
public static int[] generatePrimes(int maxValue) {
if (maxValue < 2)
return new int[0];
else {
uncrossIntegersUpTo(maxValue);
crossOutMultiples();
putUncrossedIntegersIntoResult();
return result;
}
}
private static void uncrossIntegersUpTo(int maxValue) {
crossedOut = new boolean[maxValue + 1];
for (int i = 2; i < crossedOut.length; i++)
crossedOut[i] = false;
}
private static void crossOutMultiples() {
int limit = determineIterationLimit();
for (int i = 2; i <= limit; i++)
if (notCrossed(i))
crossOutMultiplesOf(i);
}
private static int determineIterationLimit() {
// Every multiple in the array has a prime factor that
// is less than or equal to the root of the array size,
// so we don't have to cross out multiples of numbers
// larger than that root.
double iterationLimit = Math.sqrt(crossedOut.length);
return (int) iterationLimit;
}
private static void crossOutMultiplesOf(int i) {
for (int multiple = 2 * i; multiple < crossedOut.length; multiple += i)
crossedOut[multiple] = true;
}
private static boolean notCrossed(int i) {
return crossedOut[i] == false;
}
private static void putUncrossedIntegersIntoResult() {
result = new int[numberOfUncrossedIntegers()];
for (int j = 0, i = 2; i < crossedOut.length; i++)
if (notCrossed(i))
result[j++] = i;
}
private static int numberOfUncrossedIntegers() {
int count = 0;
for (int i = 2; i < crossedOut.length; i++)
if (notCrossed(i))
count++;
return count;
}
public static void main(String[] args) {
int[] a = generatePrimes(10);
System.out.println(Arrays.toString(a));
}
}
the program is to generate all the primes from 2 to the specified maximum.
what's about the Sieve of Eratosthenes?
The algorithm is quite simple. Given an array of integers starting at 2. Cross out all multiples of 2. Find the next uncrossed integer, and cross out all of its multiples. Repeat untilyou have passed the square root of the maximum value.
Every multiple in the array has a prime factor that is less than or equal to the root of the array size,
so we don't have to cross out multiples of numbers larger than that root.
multiple here means the number which is not a prime, it has a factor, and must have a prime factor which is less than or equal to its root.
素数,合数。
分享到:
相关推荐
Matlab program generates a unit impulse signal.
The scheme is based on measured data and interpolation method, and generates G modified current reference for the precise control of torque regardless of operating temperature and manufacturing ...
due to the complexity and diversity of linguistic representations, it is challenging to build a framework that accurately extracts such sentiment. We propose a semi-supervised framework for generating...
This method is called model order reduction (MOR), which reduces the complexity of the original large system and generates a reduced-order model (ROM) to represent the original one. Readers will gain...
The ST7701SN, a 16.7M-color System-on-Chip (SOC) driver LSI designed for small and medium sizes of TFT LCD display, is capable of supporting up to 480RGBX960 in resolution which can transmit graphic ...
Many species of owl, including the barn and barred owl, use both visual and bi-aural location to search for prey around dusk and at night. Their bi-aural location system has a maximum sensitivity ...
% rpiid - Generates a sequence of i.i.d. random variables, various p.d.f.'s % trispect - Computes 2-D slice of true trispectrum of ARMA process % % Quadratic Phase Coupling (QPC) % qpcgen - ...
DOE 试验设计 设计阶段 In statistics, an experiment refers to any process ...of the inputs (factors) to a process (or product) in order to observe the corresponding changes in the outputs (responses).
This tool also helps manage JAR files, javadoc - the documentation generator, which automatically generates documentation from source code comments, jdb - the debugger, jps - the process status tool,...
- FIX: In "Windows ClearType" font rendering mode (OS Windows mode) the "garbage" pixels can appear from the right and from the bottom sides of the painted rectangle of the TFlexText object....
以几乎均匀的分布在任意维度上生成点的最佳采样分布 ...Generates an optimally-sampled distribution of points in arbitrary dimensions with almost-uniform distribution.version of MAXIMIN.
A simple program that generates non repeating numbers at random in certain ranges.
SA0033327 - $$...$$ macro usage with SQL Server environments, in certain cases may trigger multiple executions of the same macro. SA0033398 - Schema compare raises silent Out of Memory exception and ...
This method is called model order reduction (MOR), which reduces the complexity of the original large system and generates a reduced-order model (ROM) to represent the original one. Readers will gain...
The method generates convincing imagery of fur at interactive rates for models of moderate complexity. Furthermore, the scheme allows real-time modification of viewing and lighting conditions, as ...
When he was called in the objects placed on the scale, the weight and belt scales body through to weighing transducer, sensor generates electricity effect - the weight of the object, will be ...
Using a well-conceived incident response plan in the aftermath of an online security breach enables your team to identify attackers and learn how they operate. But, only when you approach incident ...
数据库系统概念(第六版)里的课后习题答案,非常好的资源!
of a nonlinear program (NLP) local solver that generates a KKT point of the constructed approximation to PCDP at each iteration if this problem is indeed feasible; (ii) existence of a Slater point of ...
CMake generates native makefiles and workspaces that can be used in the compiler environment of your choice. ----------------------------- vtk-5.0.4-win32.exe ----------------------------- The ...