1. 求素数问题。埃拉托色尼筛法(Sieve of Eratosthenes)是一种用来求所有小于N的素数的方法。从建立一个整数2~N的表着手,寻找i˂的整数,编程实现此算法,并讨论运算时间。(1)
/
/*---------------------------------------------
(1)先把1删除(现今数学界1既不是质数也不是合数)
(2)读取队列中当前最小的数2,然后把2的倍数删去
(3)读取队列中当前最小的数3,然后把3的倍数删去
(4)读取队列中当前最小的数5,然后把5的倍数删去
(5)如上所述直到需求的范围内所有的数均删除或读取
*/
#include <iostream>
/*
//io代表输入输出,manip是manipulator(操纵器)的缩写,
*在c++上只能通过输入缩写才有效主要是对cin,cout之类的
一些操纵运算子,比如setfill,setw,setbase,setprecision等等。
它是I/O流控制头文件,就像C里面的格式化输出一样.
*/
#include <iomanip>
using namespace std;
const int MAX=100000;
typedef long DataType;
typedef class TagLinearList //typedef是定义了一种类型的新别名, 能隐藏平台相关的数据类型。
{
public:
DataType data[MAX];//将线性表定义为一个一维数组
int length;//线性表中实际元素的个数,空表时置为0
}SeqList;
void InitLinearList(SeqList& L);
void PrintList(const SeqList& L);
bool InsList(SeqList& L, const DataType e);
void Ailantuoni(SeqList& L,const DataType n);
int main()
{
SeqList L1;
InitLinearList(L1);
int w;
cout<<"请输入你要查看的最大值(1~100000):"<<endl;
cin>>w;
for (int k = 0; k <=w;k++)
if (!InsList(L1, k))
cout << "Insert one element in a list is fail!" << endl;
PrintList(L1);
Ailantuoni(L1,w);
cout<<"这是本质的处理方式"<<endl;
PrintList(L1);
return 0;
}
void Ailantuoni(SeqList& L,const DataType n)
{
for(int i=2;i<n;i++)
if(L.data[i])
for(int j=i;j*i<=n;j++)
L.data[j*i]=0;
cout<<"这是整理后的结果"<<endl;
for(int m=2;m<=n;m++)
if(L.data[m])
{
int k;
if(0==k%10)
{
cout << endl;
k++;
}
{
cout <<setw(5)<< L.data[m] << " ";//setw(5)表示输出占5位,setw( n ) 设域宽为n个字符
k++;
}
}
cout<<endl;
}
void InitLinearList(SeqList& L)
{
L.length = 0;
return ;
}
///输出数据
void PrintList(const SeqList& L)
{
for (int i = 0; i < L.length; i++)
{
if (0 == i % 10)
cout << endl;
cout <<setw(5)<< L.data[i] << " ";
}
cout<<endl;
}
/生成数据
bool InsList(SeqList& L, const long e)
{
if (L.length <= MAX)
{
L.data[L.length] = e;
L.length++;
return true;
}
else
{
cout << "The largest space of the LinearList is " << MAX << endl;
cout << "There is no space to store the element else!" << endl;
}
return false;
}