最近在leetCode上刷提,还是满锻炼人的,为以后面试打基础吧。不多说下面开始。
问题:求[2,n]之间的素数的个数。
来源:leetCode OJ
提示:
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 of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
先让我们写一个函数isPrime用于判断给定的数是否是素数,为了判别总一个数是否是素数,我们需要依次检查比这个数小的数能否整除n。那么函数isPrime的时间复杂度就将是O(n),因此总体的时间复杂度就会达到O(n2),我们能做的更好吗?
第一次尝试
预备知识
① 什么是素数:素数(又叫质数),与之相反的是合数。如果只考虑非负数范围内,一个大于1的数,它只能被 1 和 他本身整除。这样的数就是素数。
② 0 和 1既不是质数也不是合数。
③ 素数定理:如果一个数x是素数,那么在整数范围[2,√x ]之间,找不到任何能整除x 的整数。因此,我们不必对 [2, n) 的所有整数去尝试,而只需要对 [2,√x]之间的数尝试整除就OK了,节约了时间。
#include
#include
#include
#include
using namespace std;
/**
作用:判断一个数是否是素数
参数x:待判断的素
返回:是素数返回true,否则返回false
*/
bool isPrime(int x)
{
for(int i=;i<=int(sqrt(x));++i)
{
if(x%i==) return false;
}
return true;
}
/**
作用:统计[2,n]之间的素数的个数
参数:n
返回:素数的个数
*/
int countPrimes(int n) {
int count=;
if(n
for(int i=;i<=n;++i)
{
if(isPrime(i)) //如果 i为素数
{
++count;
}
}
return count;
}
int main()
{
clock_t start = clock();
int total &