码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 204. Count Primes

时间:2018-11-15 14:33:13      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:ati   for   problem   nat   NPU   div   mes   pre   ber   

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

标签:ati   for   problem   nat   NPU   div   mes   pre   ber   

原文地址:https://www.cnblogs.com/zlrrrr/p/9963197.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!