Java improvements - which are likely possible in other languages #491
ronlamb
started this conversation in
Improvement suggestions
Replies: 2 comments 2 replies
-
One thing I just noticed when I typed this is the for loop in solution_2 and solution_1 are very similar the main difference is that solution_1 has for (var num = factor * factor; num <= this.sieveSize; num += factor * 2 While solution_2 has for (var num = factor * 3; num <= this.sieveSize; num += factor * 2) I tried both versions, and the times are not much different. Not sure for validating implementations, which should be used. |
Beta Was this translation helpful? Give feedback.
1 reply
-
Note that |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Below are some improvements I found in the Java version of the Primes code.
The following changes are for the while loop in runSeive for solution_1. Similar changes can be made to solution_2, and likely other languages that only keep an array of the odd numbers
The first for loop increments each number by one. Since all prime numbers > 2 are odd, the even numbers can be skipped, and incrementing by two reduces by half the number of values to check,
As shown below
With the above change, the value checked inside the loop is guaranteed to be odd, the call to getBit which checks for even numbers, and if even returns true, otherwise returns the current status. Is no longer needed in the loop.
Instead the second half of the statement inside getBit, !dataset[index >> 1], can be substituted for the call to getBit(num)
Finally the loop setting all multiples of the current prime number, shown below, can also be simplified
Since the loop already is skipping all even values, the check for even in the call to clear bit is not needed, and the call to clearBit itself can be removed, and replaced with, **dataSet[num >> 1] = true; **.
The array is set to true, since the implementation for solution_1 uses false to signify prime and true, non-prime, to eliminate the need to all values to true first.
The loop then becomes
The function clearBit is no longer needed, and can be deleted. Since getBit is used in the validation section, it is still needed.
The entire while loop in runSieve can then me updated as follows Including comments added.
The changes below (tested in Java 16 on an Ryzen 5900X) added around 900 additional passes.
To
Beta Was this translation helpful? Give feedback.
All reactions