素数产生:
package com.prime;
public class PrimeGenerator {
private static boolean[] crossedOut;
private static int[] reslut;
public static int[] generatePrimes(int maxValue){
if(maxValue<2){
return new int[0];
}else{
uncrossIntegersUpTo(maxValue);
crossedOutMultiples();
putUncrossedIntegersIntoResult();
return reslut;
}
}
private static void putUncrossedIntegersIntoResult() {
reslut = new int[numbersOfUncrossedIntegers()];
for (int j = 0,i=2; i < crossedOut.length; i++) {
if(notCrossed(i))
reslut[j++] = i;
}
}
private static int numbersOfUncrossedIntegers() {
int count = 0;
for (int i = 2; i < crossedOut.length; i++) {
if(notCrossed(i))
count++;
}
return count;
}
private static void crossedOutMultiples() {
int limit = determineIterationLimit();
for(int i=2;i<=limit;i++){
if(notCrossed(i)){
crossedOutMultiplesOf(i);
}
}
}
private static void crossedOutMultiplesOf(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 int determineIterationLimit() {
double iterator = Math.sqrt(crossedOut.length);
return (int) iterator;
}
private static void uncrossIntegersUpTo(int maxValue) {
crossedOut = new boolean[maxValue+1];
for (int i = 2; i < crossedOut.length; i++) {
crossedOut[i] = false;
}
}
}
测试程序:
package com.prime;
import junit.framework.TestCase;
import junit.textui.TestRunner;
public class TestGeneratePrimes extends TestCase{
public TestGeneratePrimes(String name){
super(name);
}
public void testPrimes(){
int[] nullArray = PrimeGenerator.generatePrimes(0);
assertEquals(nullArray.length, 0);
int[] minArray = PrimeGenerator.generatePrimes(2);
assertEquals(minArray.length, 1);
assertEquals(minArray[0], 2);
int[] threeArray = PrimeGenerator.generatePrimes(3);
assertEquals(threeArray.length, 2);
}
public void testExhaustive(){
for (int i = 0; i < 500; i++) {
verifyPrimeList(PrimeGenerator.generatePrimes(i));
}
}
public void verifyPrimeList(int[] list){
for (int i = 0; i < list.length; i++) {
verifyPrime(list[i]);
}
}
public void verifyPrime(int n){
for (int i = 2; i < n; i++) {
assert(n%i!=0);
}
}
public static void main(String[] args) {
TestRunner.main(new String[]{"com.prime.TestGeneratePrimes"});
int a[] = PrimeGenerator.generatePrimes(3);
for(int i:a){
System.out.println(i);
}
}
}
转载于:https://my.oschina.net/fangfeiAI/blog/330166