1 PackagecountPrimes204;2 /*3 * Description:4 * Count The number of prime numbers less than a non-negative number, N.5 */6 Public classSolution {7 //Time Limit exceeded8 /*9 public static int countprimes (int n) {Ten int number=0; One for (int i=0;i<n;i++) A if (IsPrime (i) ==true) - number++; - return number; the } - Public Static Boolean isprime (int n) { - if (n <= 3) - return n > 1; + else if (n%2==0| | n%3==0) - return false; + else{ A for (int i=2;i<=math.sqrt (n); i++) { at if (n%i = = 0) - return false; - } - } - return true; - } in */ - to Public Static intCountPrimes (intN) { + //Boolean default is False - Boolean[] Isprime=New Boolean[n]; the intNumprime=0; * for(inti=2;i<n;i++){ $ if(isprime[i-1]==false){Panax Notoginsengnumprime++; - for(intj=2;i*j<n;j++) theisprime[i*j-1]=true; + } A } the returnNumprime; + } - Public Static voidMain (string[] args) { $ //TODO auto-generated Method Stub $System.out.println (CountPrimes (15000000)); - Boolean[] Isprime=New Boolean[2]; -System.out.println (isprime[0]); the } - //ReferenceWuyi Public intCountPrimes2 (intN) { the Boolean[] Notprime =New Boolean[n]; - intCount = 0; Wu for(inti = 2; I < n; i++) { - if(Notprime[i] = =false) { Aboutcount++; $ for(intj = 2; I*j < n; J + +) { -NOTPRIME[I*J] =true; - } - } A } + returncount; the } -}
Leetcode----204. Count Primes (Java)