csdn_spider/blog/ds19991999/原创-- 用C++求100以内的素数.md

52 lines
1.3 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 原创
用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...的倍数
} //经过两轮筛选相当于去掉了2357...的倍数
}
//打印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] << " ";
}
```