204. Count Primes

来源:互联网 发布:ad7606 数据手册 编辑:程序博客网 时间:2024/05/16 07:39

除了C语言课本里方法,另一种求质数的算法:
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
给出的参考代码:

public int countPrimes(int n) {   boolean[] isPrime = new boolean[n];   for (int i = 2; i < n; i++) {      isPrime[i] = true;   }   // Loop's ending condition is i * i < n instead of i < sqrt(n)   // to avoid repeatedly calling an expensive function sqrt().   for (int i = 2; i * i < n; i++) {      if (!isPrime[i]) continue;      for (int j = i * i; j < n; j += i) {         isPrime[j] = false;      }   }   int count = 0;   for (int i = 2; i < n; i++) {      if (isPrime[i]) count++;   }   return count;}
0 0
原创粉丝点击