LeetCode204题
解法一
欧拉算法
class Solution { public int countPrimes(int n) {
byte[] check = new byte[n];//用来标记是否已经访问过了,如果访问过了就打1,没访问过打0
int[] primeList = new int[n]; //用来记素数
int count = 0;//用来记录素数个数
for(int i = 2;i< n;i++) {
if(check[i]==0) { //打了1的就不会再看了,重复赋值浪费时间
primeList[count++] = i; //count变量记录素数个数,数组记录已知的素数的值
}
for(int j=0;j<count&&i*primeList[j]<n;j++) {
if(i*primeList[j]>n) {
break;
}
check[i*primeList[j]] = 1; //标记 x=i*primeList[j],x位置是我访问过的位置,打1
if(i%primeList[j]==0) { //这一部分不好理解,比方说6,之前访问过(2,3),那么6%2==0,不用再检查6%3了,真正负责记录数据的是count变量
break;
}
}
}
return count;
链接:https://leetcode-cn.com/problems/two-sum/solution/shi-yong-ou-la-suan-fa-by-deep-dark/
解法二
厄拉多塞筛法
class Solution {
public int countPrimes(int n) {
int[] nums = new int[n];
for(int i=2;i<n;i++) {
nums[i] = 1;
}
int res = 0;
int t = (int)Math.sqrt(n);
for(int i=2;i<=t;i++) {
if(nums[i]==1) {
for(int j=2; j*i<n;j++) {
nums[j*i] = 0;
}
}
}
for(int i:nums) {
res+=i;
}
return res;
}
}