首先写出推法求质的程序,思想就是拿前面的质数来确定当前验证的数字为合数。从而,将为确定为合数的数确定为质数,逐渐的加到数组里。
推法求质:
#include <cstdlib>
#include <fstream>
#include <cmath>
using namespace std;
ifstream cin("zhi.in");
ofstream cout("zhi.out");
int main(int argc, char *argv[])
{
int s[20000] = {};
int n, i, j, x;
bool f;
cin >> n;
x = 0;
for ( i = 2 ; i <= n ; i++ )
{
f = true;
for ( j = 0 ; j < x && s[j] <= int(sqrt(i * 1.0) + 0.5) ; j++ )
if (i % s[j] == 0)
{
f = false;
break;
}
if ( f )
s[x++] = i;
}
cout << s[0];
for ( i = 1 ; i < x ; i++ )
if ( s[i] )
cout << " " << s[i];
cout << endl << x << endl;
//system("PAUSE");
return EXIT_SUCCESS;
}
然后是筛法求质,思想就是,要把所有的质数的倍数筛掉(即筛掉合数)。从而留下的就都是质数。
#include <cstdlib>
#include <fstream>
using namespace std;
ifstream cin("zhi.in");
ofstream cout("zhi.out");
int main(int argc, char *argv[])
{
int s[50000] = {};
int n, i, j;
cin >> n;
for ( i = 2 ; i <= n ; i++ )
s[i] = 1;
for ( i = 2 ; i <= n ; i++ )
if (s[i] == 1)
for (j = 2 * i ; j <= n ; j += i)
s[j] = 0;
cout << 2;
for ( i = 3 ; i <= n ; i++ )
if ( s[i] )
cout << " " << i;
cout << endl;
//system("PAUSE");
return EXIT_SUCCESS;
}