【Leetcode】204. Count Primes

来源:互联网 发布:淘宝直播卖什么最好卖 编辑:程序博客网 时间:2024/06/08 17:40

思路:

素数不能被比它小的整数整除, 建一个boolean 数组, 从2开始, 把其倍数小于n的都删掉。

注意inner loop从i开始, 比i小的会在以前就被check过。

public class Solution {    public int countPrimes(int n) {        boolean[] isPrime = new boolean[n];        for (int i = 2; i < n; i++)             isPrime[i] = true;        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;    }}
Runtime:36ms

1 0
原创粉丝点击