计数质数

https://leetcode.cn/problems/count-primes/description/

class Solution {
public:
    bool isPrime(int x) {
        for (int i = 2; i * i <= x; ++i) {
            if (x % i == 0) {
                return false;
            }
        }
        return true;
    }

    int countPrimes(int n) {
        int ans = 0;
        for (int i = 2; i < n; ++i) {
            ans += isPrime(i);
        }
        return ans;
    }
};

 

posted @ 2025-07-20 18:07  最近饭吃的很多  阅读(5)  评论(0)    收藏  举报