暴力解法
暴力就是挨着对数进行相除,挨着判断,没有什么好说的
// 计算素数个数 public static int countPrimes(int n) { int count = 0; for (int i = 2; i < n; i++) { if (isPrime(i)) { count++; } // count+=isPrime(i)?1:0; } return count; } // 暴力搜索, 挨着进行取余进行判断。是素数返回true,不是返回false public static boolean isPrime(int x) { //或者i*i<=x 因为如果2*6 = 12, 6*2=12,因此只用判断到中间即可 for (int i = 2; i < x; i++) { if (x % i == 0) { return false; } } return true; }
埃塞法
因为如果2是素数,那么2*2=4,2*3=6,2*4=8,2*5=10,2*6=12,2*7=14,2*8=16,2*9=18,2*10=20,2*11=22,2*12=24,2*13=26,2*14=28,2*15=30,2*16=32,这些注定不是素数为合数y
因此可以创建一个数组对数据进行标注,然后就知道哪些为素数,进行计数
public static int eratosthenes(int n) { boolean[] isPrime = new boolean[n]; //false 表示素数,true表示合数,默认为false,我们要将合数标记,为合数的跳过 //因为如果2是素数,那么2*2=4,2*3=6,2*4=8,2*5=10,2*6=12,2*7=14,2*8=16,2*9=18,2*10=20,2*11=22,2*12=24,2*13=26,2*14=28,2*15=30,2*16=32,这些注定不是素数为合数 // Arrays.fill(isPrime, true); //true 表示素数,false表示合数 int count = 0; for(int i = 2; i < n; i++){ if(!isPrime[i]){ count++; for(int j = 2 * i; j < n; j += i){ //因为i为外面的值,不能对i进行+1所有对j+=i,相当于每次把j+2和i+1是一个效果 isPrime[j] = true; } } return count; } return 0; }
这道题比较容易