To calculate the number of prime numbers within n (not including n) in a relatively efficient way
Solution 1 Exhaustive
intcountPrimes(int n){
int count =0;for(int i =2; i < n; i++)if(isPrim(i)) count++;return count;}// 判断整数 n 是否是素数booleanisPrime(int n){
for(int i =2; i * i < n; i++)if(n % i ==0)// 有其他整除因子returnfalse;returntrue;}
Solution 2 Sieve of Eratosthenes
intcountPrimes(int n){
boolean isPrim[]=newboolean[n];
Arrays.fill(isPrim,true);for(int i =2; i * i < n; i++){
if(isPrim[i]){
for(int j = i * i; j < n; j+=i){
isPrim[j]=false;}}}int count =0;for(int i =2; i < n; i++){
if(isPrim[i])
count++;}return count;}