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

[leetcode] Count Primes

时间:2015-05-04 21:41:10      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

Count Primes

Description:

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

click to show more hints.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Have you met this question in a real interview?
 
class Solution
{
public:
  int countPrimes(int n)
  {
    vector<int> a(n);
    for(int i=0; i<n; i++)
      a[i] = i;

    for(int i=1; i * 2<= n; i++)
    {
      if(i == 1) 
      {
        a[i] = 0;
        continue;
      }

      for(int j = i + i; j < n; j += i)
      {
        if(a[j] != 0)
          a[j] = 0;
      }
    }

    int count = 0;
    for(int i=0; i<n; i++)
    {
      cout << a[i] << " ";
      if(a[i] != 0)
      {
        count++;
      }
    }
    cout << endl;

    return count;
  }
};

 

[leetcode] Count Primes

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4477116.html

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