首页 > 其他 > 详细

Leetcode problem-204 Count Primes 题解

时间:2016-11-14 15:05:36      阅读:122      评论:0      收藏:0      [点我收藏+]

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 题解

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!