The code of previous post is a high-cost code that "searches the entire list, divides it, and sifts it", as pointed out by @swordone. It turned out. So, based on the hint given by @swordone, I made a major correction to the code.
The differences from the previous code are as follows.
List <Integer>
to boolean []
.PrimeNumberFinder.java
static void printPrimeNumbers2(int maxNumber) {
//Step 1: Put "integer from 2 to upper limit" in the search list.
boolean[] targetNumbers = new boolean[maxNumber + 1];
Arrays.fill(targetNumbers, true);
targetNumbers[0] = false;
targetNumbers[1] = false;
//Prime number list
List<Integer> primeNumbers = new ArrayList<Integer>();
int sqrt = (int) Math.sqrt(maxNumber);
//Step 3: Continue the sieving operation until the first value in the search list reaches the square root of the argument.
for(int i=2; i<=sqrt; i++) {
//Step 2: Make the first number in the search list a prime number and screen multiples from the search list.
//* At this time, the number that has already been sieved (false) is excluded.
int firstNum = i;
if (targetNumbers[i]) {
for (int j=i*firstNum; j<targetNumbers.length; j+=firstNum) {
targetNumbers[j] = false;
}
}
}
//Step 4: Move the values remaining in the search list to the prime number list and finish the process.
for (int i=2; i<targetNumbers.length; i++) {
if (targetNumbers[i]) {
primeNumbers.add(i);
}
}
//Display of prime numbers
System.out.println(primeNumbers.stream().map(pNum -> pNum.toString()).collect(Collectors.joining("\t")));
}
The upper limit is |
The upper limit is |
The upper limit is |
The upper limit is |
|
---|---|---|---|---|
Last code | 54ms | 55ms | 61ms | 102ms |
This code | 0ms | 1ms | 1ms | 9ms |
Recommended Posts