Count Primes [leetcode]

Description:

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

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

Hint:

  1. Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity ofisPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better

题目要求输入一个N返回一个小于N的素数数量,在ACM的竞赛中,常常使用打表实现,即使用数组记录每个数是否素数然后直接调用数据。但是明显在这里不能用这样的方式。
这题的数据量最大达到了1500000,int类型的数组已经存不下,所以必须用bool类型去记录数据。(新技能Get)同时可调用参数n,去动态建立数组大小:如bool count[n];不用去猜数组需要达到多大。
c++代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<cstdlib>
#include<map>
#include<cmath>
#include<iostream>
using namespace std;
class Solution {
public:
    int countPrimes(int n) {
          if(n < 2)
            return 0;
        bool count[n];//可动态生成数组大小,且用bool量记录数组数据状态 
        memset(count,0,sizeof(count));
        count[0] = count[1] = true;
        for(int i = 2;i<=sqrt(n);i++)
        {
        	if(!count[i])
        	{
        		for(int j = 2;;j++)
        		{
        			if(i*j > n)
        				break;
        			count[i*j] = true;
				}
			}
        }
        int sum = 0;
        for(int i = 1;i<n;i++)
        {
        	if(!count[i])
        	{
        		sum++;
        	}
        }
        return sum;
    }
};
int main()
{
	Solution s;
	int n;
	while(~scanf("%d",&n))
	{
		cout << s.countPrimes(n) << endl;
	}
}

其中main函数主要作为测试用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值