Several algorithms for comparison primes (prime number) of

Find all prime natural numbers specified range, it is not difficult to achieve, but which algorithm is the most efficient and fastest is the key, I list several algorithms:

1, to be judged value smaller than that and not less than 2 for all the logarithmically remainder 
public static List <Integer> getprimeV1 (int max) {
List <Integer> List = new new the ArrayList <> ();
Boolean In Flag;
int Times = 0;
for (int I = 2; I <= max; I ++) {
In Flag = to false;
IF (In Flag!) {
for (int J = 2; J <I; J ++) {
Times ++;
IF (I% J == 0) {
In Flag to true =;
BREAK;
}
}
}
IF (In Flag) {!
List.add (I);
}
}
System.out.println ( "cycles:" times +);
return List;
}


2, to be all primes smaller than its value determines the number of remainder
public static List <Integer> getprimeV2 (int max) {
List <Integer> = new new List the ArrayList <> ();
Boolean in Flag;
int times = 0;
for (int I = 2; I <= max; I ++) {
In Flag = to false;
IF (I> 2) {
for (Integer NUM: List) {
Times ++;
IF (I% NUM == 0) {
In Flag = to true;
BREAK;
}
}
}
IF (in Flag!) {
List.add (I);
}
}
System.out.println ( "cycles:" times +);
return List;
}
. 3, the value is determined to be larger than it is and is not All logarithmically remainder of the square root and not less than two
public static List <Integer> getprimeV3 (int max) {
List <Integer> List = new new the ArrayList <> ();
Boolean in Flag;
int Times = 0;
for (int I = 2 ; I <= max; I ++) {
In Flag = to false;
IF (In Flag) {!
for (int J = 2; J <= the Math.sqrt (I); J ++) {
Times ++;
IF (I% J == 0) {
= to true In Flag;
BREAK;
}
}
}
IF (In Flag!) {
List.add (I);
}
}
System.out.println ( "cycles:" Times +);
return List;
}
. 4, the value to be determined and primes all not greater than its square root modulo the number of
public static List <Integer> getprimeV4 (int max) {
List <Integer> List = new new the ArrayList <> ();
Boolean in Flag;
int Times = 0;
for (int I = 2 ; I <= max; I ++) {
In Flag to false =;
IF (I> 2) {
for (int J = 0; List.get (J) <= the Math.sqrt (I); J ++) {
Times ++;
IF (I List.get% (J) == 0) {
In Flag to true =;
BREAK;
}
}
}
IF (In Flag) {!
List.add (I);
}
}
System.out.println ( "cycles:" Times +);
return List;
}
For the above four algorithms:
1) When I when its argument is 100, the number of cycles obtained from top to bottom are as follows:
1133, 411,236, 181, they consume very short time, are not comparable, it is possible for a larger parametric test;
2) when I pass parameters 1,000,000, they consume about a time from the top down are as follows:
150s, 80s, 0.8s, 0.3s
from the test results, different algorithms, computational efficiency is very different, learn algorithm for improving the efficiency of great help. If better algorithm, corrections and additions are welcome, thank you.

Guess you like

Origin www.cnblogs.com/XiaoyangBoke/p/11236855.html