(1) Time spent without optimization:
public class Primenumber {public static void main (string[] args) { long start = System.currenttimemi Llis (); Boolean flag = False; for (int i = 2, I <= 100000; i++) {for (int j = 2; J < I; j + +) {if (i% j = 0) {flag = True;} } if (flag = = False) System.out.print (i+ ""); Flag = False;} long end = System.currenttimemillis (); System.out.println ("\ n" + (end- start));}}
The time spent is: 27038ms
(2) Optimize one: Inner loop judgment, when False is true, you can jump out of the inner layer loop
public class Primenumber {public static void main (string[] args) { long start = System.currenttimemi Llis (); Boolean flag = False; for (int i = 2, I <= 100000; i++) {for (int j = 2; J < I; j + +) {if (i% j = 0) {flag = True; br Eak;}} if (flag = = False) System.out.print (i+ ""); Flag = False;} long end = System.currenttimemillis (); System.out.println ("\ n" + (end- start));}}
The time spent is: 2424ms
(3) Optimization two: The inner loop only need to cycle to the root of I, you can end (note including the root of i)
public class Primenumber {public static void main (string[] args) { long start = System.currenttimemi Llis (); Boolean flag = False; for (int i = 2, I <= 100000; i++) {for (int j = 2; J <= Math.sqrt (i); + j) {if (i% J = = 0) {flag = t Rue; break;}} if (flag = = False) System.out.print (i+ ""); Flag = False;} long end = System.currenttimemillis (); System.out.println ("\ n" + (end- start));}}
The time spent is: 191ms
Java optimized prime number within 100,000 of output