Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int main()
- {
- int low, high;
- char again='y';
- high=low=0;
- int firstn;
- int newarrsize=0;
- cout<<"tThe Sieve of Eratosthenes Algorithm"<<endl<<endl;
- do{
- //code to get low and high from user
- int* thearr= arr(high);
- for(int ix=0; ix<low;++ix){
- thearr[ix]=-1;
- }
- firstn=firstprime(high,thearr);
- do{
- crossout(high,thearr,firstn);
- firstn=firstprime(high,thearr);
- }while(firstn<= sqrt(high));
- if(firstn>sqrt(high))
- findzeros(thearr,high);
- int* thenewarr= primearr(thearr,high,newarrsize);
- cout<<"The prime numbers from "<<low<<" to "<<high<<" are: "<<endl;
- for(int ix=0; ix<=high; ++ix){
- cout<<thearr[ix]<<" ";
- }
- cout<<endl<<endl;
- cout<<endl<<endl;
- cout<<"Try again with new boundaries? (y/n):"<<endl;
- cin>>again;
- delete[] thearr;
- delete[] thenewarr;
- }while(again=='y');
- return 0;
- }
- int* arr(int size){
- int* thearray = new int[size]();
- thearray[0] = -1;
- thearray[1] = -1;
- return thearray;
- }
- int firstprime(int size, int arr[]){
- int* end = arr + size;
- int* begin = arr;
- while(begin<end){
- if(*begin==0)
- return *begin;
- begin++;
- }
- return -1;
- }
- void crossout(int size, int*arr, int factor){
- int* end = arr + size;
- int* begin = arr;
- begin[factor]=1;
- while(begin<end){
- if(*begin==factor)
- *begin=-1;
- factor+=factor;
- }
- }
- void findzeros(int arr[], int size){
- int* end = arr + size;
- int* begin = arr;
- while(begin<end){
- if(*begin==0)
- *begin=1;
- begin++;
- }
- }
- int* primearr(int arr[], int size, int& newarrsize){
- int count=0;
- int* end = arr + size;
- int* begin = arr;
- while(begin<end){
- if(*begin==1)
- ++newarrsize;
- begin++;
- }
- begin=arr;
- int *newarray= new int[newarrsize];
- while(begin<end){
- if(*begin==1){
- newarray[count]=*begin;
- }
- begin++;
- }
- return newarray;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement