Description:
Count the number of prime numbers less than a non-negative number, n.
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Resolution: A natural number greater than 1, the natural number can be divided by 1 and its own, then the natural number is called Prime.
Method One: Brute force, Time complexity O (n^2)
The code is as follows:
public class Solution {public int countprimes (int n) { if (n<=2) return 0; int num=0; for (int i=2;i<n;i++) if (IsPrime (i)) num++; return num; } public boolean isprime (int i) {for (int j=2;j<i;j++) { //or for (int j=2;j<=i/2;j++), or for (int j=2;j*j <i;j++); if (i%j==0) return false; } return true; }}
Run Result: timeout, time complexity O (n^2)
Method 2: Multiples of prime numbers are excluded.
The code is as follows:
public class Solution {public int countprimes (int n) { if (n<=2) return 0; Boolean []isprime=new boolean[n]; int sum=0; for (int i=2;i<n;i++) { isprime[i]=true; } for (int i=2;i<n;i++) { if (Isprime[i]) {for (int j=2;j*i<n;j++) { isprime[j*i]=false;}} } for (int i=2;i<n;i++) { if (isprime[i]==true) sum++; } return sum; } }
Run Result: Time complexity O (n).
(easy) Leetcode 204.Count Primes