Requirements: Prints the prime and non-prime numbers in 2-100000. (Prime definition: in a natural number greater than 1, there are no other factors other than 1 and itself)
1. Conventional way--for positive integer n, if all integers from 2 to zero are not divisible, then n is prime:
//sqrt Method Public Static voidPrintPrime1 (intnum) { Boolean[] Isprimes =New Boolean[num + 1]; for(inti = 2; i < isprimes.length; i++) {Isprimes[i]=true; } for(inti = 3; I <= num; i++) { for(intj = 2; J <= Math.sqrt (i); J + +) { if(i% j = 0) {Isprimes[i]=false; Break; }}} System.out.print ("Prime numbers are:"); for(inti = 2; i < isprimes.length; i++) { if(Isprimes[i]) {System.out.print (i+ " "); }} System.out.println (""); System.out.print ("Non-prime numbers are:"); for(inti = 2; i < isprimes.length; i++) { if(!Isprimes[i]) {System.out.print (i+ " "); } } }
Note that the use of a Boolean array for the determination of the prime number and the final result of the printing, avoid using two containers to separate each of the two pieces of content to be printed.
2. The Screening method
//wagered Sieve Method Public Static voidPrintPrime2 (intnum) { Boolean[] Isprimes =New Boolean[num + 1]; for(inti = 2; i < isprimes.length; i++) {Isprimes[i]=true; } for(inti = 2; i < num; i++) { if(Isprimes[i] = =true) { for(intj = 2; I * j <= num; J + +) {isprimes[i* j] =false; }}} System.out.print ("Prime numbers are:"); for(inti = 2; i < isprimes.length; i++) { if(Isprimes[i]) {System.out.print (i+ " "); }} System.out.println (""); System.out.print ("Non-prime numbers are:"); for(inti = 2; i < isprimes.length; i++) { if(!Isprimes[i]) {System.out.print (i+ " "); } } }
Finally, a main method is provided to complete the invocation and performance comparison of two methods:
Public Static voidMain (string[] args) {LongTimePoint1 =System.currenttimemillis (); PrintPrime1 (100000); LongTimePoint2 =System.currenttimemillis (); System.out.println (); PrintPrime2 (100000); LongTimePoint3 =System.currenttimemillis (); System.out.println (); System.out.println ("Sqrt Method Time:" + string.valueof (timepoint2-timepoint1));//390 MsSystem.out.println ("The time spent on the screen:" + string.valueof (Timepoint3-timepoint2));//297 Ms}
Java Print Prime number (prime number)