#Leetcode# 204. Count Primes
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 204. Count Primes相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/count-primes/
Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
代码:
class Solution { public: int countPrimes(int n) { int ans = 0; if(n == 0 || n == 1) return 0; for(int i = 2; i < n; i ++) if(isPrime(i)) ans ++; return ans; } bool isPrime(int x) { for(int i = 2; i * i <= x; i ++) if(x % i == 0) return false; return true; } };
以上是关于#Leetcode# 204. Count Primes的主要内容,如果未能解决你的问题,请参考以下文章