204. Count Primes

原创 2016年05月31日 19:55:51

204. Count Primes

Description:

Count the number of prime numbers less than a non-negative number, n.
Analysis:
大家基本都会使用这个方法啦:https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
下面程序中vector的int类型改为bool应该会更好一些。
Source Code(C++):

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

class Solution {
public:
    int countPrimes(int n) {
        if (n<2){
            return 0;
        }
        vector<int> v(n, 1);
        v.at(0)=0;v.at(1)=0;
        for(int i=2; i<sqrt((float)n); i++) {
            if(v.at(i)==1){
                for (int j=2; i*j<n; j++){
                    v.at(i*j)=0;
                }
            }           
        }
        int prime_counts=0;
        for (int i=0; i<n; i++){
            if (v.at(i)==1){
                prime_counts++;
            }
        }
        return prime_counts;
    }
};


int main() {
    Solution sol;
    cout << sol.countPrimes(0);
    cout << sol.countPrimes(100);
    return 0;
}
版权声明:转载请注明出处,谢谢。

相关文章推荐

【leetcode】【204】Count Primes

一、问题描述 Description: Count the number of prime numbers less than a non-negative number, n. ...

Count Primes - LeetCode 204

题目描述: Description: Count the number of prime numbers less than a non-negative number, n click to sho...

leetcode 204. Count Primes-素数统计

原题链接:204. Count Primes 按照题目“Show Hint”提示,如果定义一个函数,判断这个数是否是素数,那么效率会很低: public int countPrimes(int...

leetcode 204: Count Primes

问题描述:Description:Count the number of prime numbers less than a non-negative number, n.

LeetCode 204 - Count Primes

一、问题描述Description:Description:Count the number of prime numbers less than a non-negative number, nHi...

LeetCode 204:Count Primes

Description: Count the number of prime numbers less than a non-negative number, n 分析: 题目要求计算小于N的所有...

【LEETCODE】204-Count Primes

Description: Count the number of prime numbers less than a non-negative number, n. 思路: The...

LeetCode笔记:204. Count Primes

寻找小于n的质数个数

Leetcode 204题 Count Primes

题目 :Count PrimesCount the number of prime numbers less than a non-negative number, n.题目分析: 这道题目的意思是写...

Leetcode 204.Count Primes 素性检测

204.Count Primes 问题描述 Count the number of prime numbers less than a non-negative number, n. 翻译:计算小...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)