Leetcode Tags(6)Math

  一、204. Count Primes

Count the number of prime numbers less than a non-negative number, n.
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

  1.数学原理:两个质数的乘积一定是合数。一个质数乘以任何数的积都一定不是质数。(除了1)

  2.代码:需要注意的点:for (int j = 2; j * i < n; j++) notPremes[i * j] = true;

    public int countPrimes(int n) {
        boolean[] notPremes = new boolean[n];
        int count = 0;
        for (int i = 2; i < n; i++) {
            if (!notPremes[i]) {
                count ++;
                for (int j = 2; j * i < n; j++) notPremes[i * j] = true;
            }
        }
        return count;
    }

  二、

猜你喜欢

转载自www.cnblogs.com/BigJunOba/p/9577292.html