52 lines
1.3 KiB
Markdown
52 lines
1.3 KiB
Markdown
# 原创
|
||
: 用C++求100以内的素数
|
||
|
||
# 用C++求100以内的素数
|
||
|
||
```
|
||
#include<iostream>
|
||
#include<math.h>
|
||
|
||
using namespace std;
|
||
const int N = 300;
|
||
bool prime[N]; //布尔数组变量0、1
|
||
void primeNum(int a);
|
||
void printPrimeNum();
|
||
|
||
//主函数
|
||
int main()
|
||
{
|
||
primeNum(N);
|
||
printPrimeNum();
|
||
return 0;
|
||
}
|
||
|
||
//得到N以内的素数
|
||
void primeNum(int a)
|
||
{
|
||
int i,j,n=0;
|
||
for (i = 2; i<a; i++) //第一轮筛选去掉2的倍数
|
||
{
|
||
if (i % 2) prime[i] = true;
|
||
else prime[i] = false;
|
||
}
|
||
for (i = 3; i <= sqrt((double)a); i++) //double(N)是将N强制转换为双精度整型,求平方根i=3,5,7,9
|
||
{
|
||
if (prime[i])
|
||
for (j = 2*i; j<N; j += i)prime[j] = false; //第二轮筛选相当于j=ni,去掉3,5,7...的倍数
|
||
} //经过两轮筛选相当于去掉了2,3,5,7...的倍数
|
||
}
|
||
|
||
//打印N以内的素数
|
||
void printPrimeNum()
|
||
{
|
||
int i, n = 0, primeList[N];
|
||
for (i = 2; i < N; i++)
|
||
if ((i == 2) || (prime[i]))primeList[n] = i, n++;
|
||
cout <<N << "以内的素数个数为:" << n << endl<< "它们分别是:"<<endl;
|
||
for (i = 0; i < n; i++)cout <<primeList[i] << " ";
|
||
}
|
||
```
|
||
|
||
|