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.
public class Solution { List<Integer> prime = new ArrayList<>(); public int countPrimes(int n) { int res = 0; for(int i=2;i<n;i++){ if(isPrime(i)) res++; } return res; } private boolean isPrime(int n){ int m = (int) Math.sqrt(n); if(n==1) return false; for(int itt:prime){ if(itt>m) break; if(n%itt==0) return false; } prime.add(n); return true; } }
原文地址:http://blog.csdn.net/guorudi/article/details/45342911