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

Leetcode problem-204 Count Primes 题解

时间:2016-11-14 15:07:32      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:idt   ++   nbsp   top   number   开始   超时   table   body   

Leetcode problem-204 Count Primes

Count the number of prime numbers less than a non-negative number, n.

题解:这道题如果对每个小于n的数都进行判断是否为素数并计数会超时,因此采用筛法来解这题。建一个数组,从2开始, 把其倍数小于N的都删掉。

class Solution {

public:

    int countPrimes(int n) {

        vector<int>arr(n,1);

        int sum=0;

        for(int i=2;i<=n;i++)

        {

            if(arr[i]==1)

            {

                sum++;

                for(int j=i;j<n;j+=i)

                {

                    arr[j]=0;

                }

            }

 

        }

        return sum;

    }

};

Leetcode problem-204 Count Primes 题解

标签:idt   ++   nbsp   top   number   开始   超时   table   body   

原文地址:http://www.cnblogs.com/fengxw/p/6061597.html

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