Prime
Time Limit:1000MS Memory Limit:30000KB
Description
A prime is the number which can be only divide exactly by 1 or itself.
Input
There several test case. Each test case have two positive integer N,M in one line. (0<M<=N<1000000)
Output
For each test case, output one line that contain an integer that is the number of primes from N to M.
Sample Input
5 10
1 3
6 8
Sample Output
2
2
1
这道题意思是给定两个数M、N,求[M,N]中素数的个数。问题的核心显然在于判断一个数是否是素数上,判断一个数是否是素数,大家都会想到一个基本的算法:
int isPrime(int n)
{
if(n==1)
{
return 0;
}
for(int i = 2; i*i <= n; ++i)
{
if(n%i == 0)
{
return 0;
}
}
return 1;
}
这个算法的时间复杂度是O(n*sqrt(n)),对于小数据还是跑的很happy的,但是遇到题目中这种
1000000这么大的数,又要天昏地暗了。。提交时间显然会超时,因此必须采用更优化的算法,判断素数一般比较好的算法是素数筛选法,先介绍下素数筛选法的原理,这样待会看代码的时候很容易理解。素数筛选法原理:首先,我们知道对于正整数来说,除了2,要想是素数必须是奇数,但奇数不一定都是素数,因此有了这个原理,一下就能排除一般的数(全部偶数),接下来只要再把奇数中不是素数的剔除掉,所有的素数就出来了。问题又回到判断素数的问题上来了,还用上面的算法判断?即使已经排除一半的数了,上面的算法依然会超时(1000ms)。那要怎样提出奇数中的素数呢,我们知道奇数的倍数一定不是素数,那么就好写了,上代码:
#include <iostream>
using namespace std;
const int N = 1000001;
bool primeList[N];
//踢掉奇数中不是素数的数
void isPrime()
{
for(int i = 3; i*i <= N; i += 2)
{
//奇数的倍数一定不是素数
for(int j = i + i; j < N; j += i)
{
primeList[j] = false;
}
}
}
int main()
{
//偶数除了2肯定都不是素数,先把所有奇数都认为是素数,然后踢掉奇数中不是素数的
for(int i = 3; i < N; ++i)
{
if(i%2 == 0)
{
primeList[i] = false;
}
else
{
primeList[i] = true;
}
}
primeList[1] = false;
primeList[2] = true;
isPrime();
int m,n;
while(cin >> m >> n)
{
int count = 0;
for(int i = m; i <= n; ++i)
{
if(primeList[i] == true)
{
++count;
}
}
cout << count << endl;
}
return 0;
}
提交到OJ测得用时36MS,简直是高铁。。。