首页 > 代码库 > 求质数方法大总结

求质数方法大总结

最近知乎上看到一道求2000000之内的质数的个数~最近总结了下求质数的方法,

也就顺带总结了下求质数的方法

 

1、蛮力法求质数

 

 1 public class PrimeTest1 2 { 3     public static boolean isPrime(int numPrime) 4     { 5         for (int i = 2; i < numPrime; i++) 6         { 7             if (numPrime % i == 0) 8             { 9                 return false;10             }11         }12         return true;13     }14     15     public static int countPrime(int allPrime)16     {17         int count = 0;18         19         for (int i = 2; i < allPrime; i++)20         {21             if (isPrime(i) == true)22             {23                 count++;24             }25         }26         27         return count;28     }29     30     31     32     public static void main(String[] args)33     {34         final int Nmax = 100000;35         double startTime = System.currentTimeMillis();36         int primeNum = PrimeTest1.countPrime(Nmax);37         double timeSpent=(System.currentTimeMillis()-startTime)/1000;38         39         System.out.println("(method1)The prime numbers from 1 to "+Nmax+" is "+primeNum);40         System.out.println("Time spent : "+timeSpent+" s");41 42     }43 44 }

 

求质数方法大总结