rorschack

PrimeNoList

Mar 26th, 2016
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <math.h>
  4. #include <cstdlib>
  5.  
  6. //Prime No. List using SIEVE OF ERATOSTHENES
  7.  
  8. using namespace std;
  9.  
  10. int main(int argc, char *argv[]) {
  11.     int n;
  12.     vector<int> vec;
  13.     if(argc==1) {
  14.         cout << "Enter a positive decimal number: ";
  15.         cin >> n;
  16.     } else n=atoi(argv[1]);
  17.     for(int i=0;i<=n;i++) {
  18.         vec.push_back(1);//Initially assume all numbers are prime
  19.     }
  20.     vec[0]=vec[1]=0;//0 and 1 are neither prime nor composite
  21.     for(int j=2;j<=sqrt(n);j++) {
  22.         if(vec[j]==1) {
  23.             for (int k=2;k*j<=n;k++) { //Set all the multiples to 0
  24.                 vec[k*j]=0;
  25.             }
  26.         }
  27.     }
  28.     //Trial Division Method
  29.     // for(int j=2;j<=n;j++) {
  30.     //  for(int k=2;k<=sqrt(j);k++) {
  31.     //      if(j%k==0) {
  32.     //          vec[j]=0;
  33.     //          break;
  34.     //      }
  35.     //  }
  36.     // }
  37.     for(vector<int>::size_type i=2;i<=vec.size();i++) { //Only numbers left with value 1 are prime
  38.         if(vec[i]==1)
  39.             cout << i << endl;
  40.     }
  41.     return 0;
  42. }
  43.  
  44. /*
  45. Test Results:
  46. when n=99990000,
  47. Sieve of Eratosthenes method took 35.183s
  48. Trial Division Method method took 9m16.998s
  49. */
Add Comment
Please, Sign In to add comment