importjava.util.ArrayList;classSolution{publicintsolution(intn){ArrayList<Integer>primeList=newArrayList<>(1000000);intanswer=0;// Find prime numberfor(inti=2;i<=n;i++){booleanisPrime=true;for(intj=0;j<primeList.size();j++){if(i%primeList.get(j)==0){isPrime=false;break;}}if(isPrime){primeList.add(i);answer++;}}returnanswer;}}
importjava.util.Arrays;classSolution{publicintsolution(intn){// Init isPrime arrayboolean[]isPrime=newboolean[n+1];Arrays.fill(isPrime,true);isPrime[0]=false;// 0 is not primeisPrime[1]=false;// 1 is not prime// Find prime numberfor(inti=2;i<=n;i++){if(isPrime[i]){for(intj=2*i;j<=n;j=j+i){isPrime[j]=false;}}}// Get prime number countintcount=0;for(inti=0;i<isPrime.length;i++){if(isPrime[i]){count++;}}returncount;}}