[leetcode][math][hash] Count Primes

题目:

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?

最直观的想法是遍历2到n-1,同时用一张表存下来已经找到的质数,对用表中的每一个数去除当前数i,如果有能整除的,则i不是质数,如果都不能整除,则i是质数,把i放入表格,遍历完毕后,table中放的就是该小于n的所有质数,个数就是table的大小。这样做可以得到正确结果,但是超时(很久很久)。

class Solution {
public:
    int countPrimes(int n) {
	if (n <= 1) return 0;
	vector<int> primes;//存放已经找到的所有质数
	primes.push_back(2);
	for (int i = 3; i < n; ++i){
		int j = 0;
		for (; j < primes.size(); ++j){
			if (0 == i%primes[j]) break;
		}
		if (j == primes.size()) primes.push_back(i);
	}
	return primes.size();
}
};


解决该问题的一个巧妙的算法是Eratosthenes筛选算法,真是禁不住概叹 太TM妙了!

class Solution {
public:
    int countPrimes(int n) {
	if (n <= 1) return 0;
	vector<bool> isPrime(n);//isPrime[i]表示整数i是否是质数
	for (int i = 2; i < n ; ++i) isPrime[i] = true;//初始化isPrime
	//对每一个质数i进行一下操作:从i*i开始,i的所有整数倍都不是质数
	for (int i = 2; i * i < n; ++i){//!!!注意这里的循环结束条件是i*i < n
		if (isPrime[i]){//i是整数
			for (int j = i*i; j < n; j = j + i) isPrime[j] = false;
		}
	}
	//统计质数个数
	int res = 0;
	for (int i = 2; i < n; ++i){
		if (isPrime[i]) ++res;
	}
	return res;
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值