Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. int main()
  2. {
  3. int low, high;
  4. char again='y';
  5. high=low=0;
  6. int firstn;
  7. int newarrsize=0;
  8.  
  9. cout<<"tThe Sieve of Eratosthenes Algorithm"<<endl<<endl;
  10. do{
  11.  
  12. //code to get low and high from user
  13.  
  14. int* thearr= arr(high);
  15. for(int ix=0; ix<low;++ix){
  16. thearr[ix]=-1;
  17. }
  18. firstn=firstprime(high,thearr);
  19. do{
  20. crossout(high,thearr,firstn);
  21. firstn=firstprime(high,thearr);
  22. }while(firstn<= sqrt(high));
  23.  
  24. if(firstn>sqrt(high))
  25. findzeros(thearr,high);
  26.  
  27. int* thenewarr= primearr(thearr,high,newarrsize);
  28.  
  29. cout<<"The prime numbers from "<<low<<" to "<<high<<" are: "<<endl;
  30.  
  31. for(int ix=0; ix<=high; ++ix){
  32. cout<<thearr[ix]<<" ";
  33. }
  34.  
  35. cout<<endl<<endl;
  36. cout<<endl<<endl;
  37. cout<<"Try again with new boundaries? (y/n):"<<endl;
  38. cin>>again;
  39.  
  40. delete[] thearr;
  41. delete[] thenewarr;
  42.  
  43. }while(again=='y');
  44.  
  45. return 0;
  46. }
  47.  
  48. int* arr(int size){
  49. int* thearray = new int[size]();
  50. thearray[0] = -1;
  51. thearray[1] = -1;
  52. return thearray;
  53. }
  54.  
  55. int firstprime(int size, int arr[]){
  56. int* end = arr + size;
  57. int* begin = arr;
  58. while(begin<end){
  59. if(*begin==0)
  60. return *begin;
  61. begin++;
  62. }
  63. return -1;
  64. }
  65.  
  66. void crossout(int size, int*arr, int factor){
  67. int* end = arr + size;
  68. int* begin = arr;
  69. begin[factor]=1;
  70. while(begin<end){
  71. if(*begin==factor)
  72. *begin=-1;
  73. factor+=factor;
  74. }
  75. }
  76.  
  77. void findzeros(int arr[], int size){
  78. int* end = arr + size;
  79. int* begin = arr;
  80. while(begin<end){
  81. if(*begin==0)
  82. *begin=1;
  83. begin++;
  84. }
  85. }
  86.  
  87. int* primearr(int arr[], int size, int& newarrsize){
  88. int count=0;
  89. int* end = arr + size;
  90. int* begin = arr;
  91. while(begin<end){
  92. if(*begin==1)
  93. ++newarrsize;
  94. begin++;
  95. }
  96. begin=arr;
  97.  
  98. int *newarray= new int[newarrsize];
  99. while(begin<end){
  100. if(*begin==1){
  101. newarray[count]=*begin;
  102. }
  103. begin++;
  104. }
  105. return newarray;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement