0

I tried sieve of Eratosthenes: Following is my code:

void prime_eratos(int N) {
    int root = (int)sqrt((double)N);
    bool *A = new bool[N + 1];
    memset(A, 0, sizeof(bool) * (N + 1));
    for (int m = 2; m <= root; m++) {
        if (!A[m]) {
            printf("%d  ",m);
            for (int k = m * m; k <= N; k += m)
                A[k] = true;
        }
    }

    for (int m = root; m <= N; m++)
        if (!A[m])
            printf("%d  ",m);
    delete [] A; 
}

int main(){

    prime_eratos(179426549);
    return 0;
}

It took time : real 7.340s in my system.

I also tried Sieve of Atkins(studied somewhere faster than sieve of Eratosthenes).

But in my case,it took time : real 10.433s .

Here is the code:

int main(){
    int limit=179426549;
    int x,y,i,n,k,m;
    bool *is_prime = new bool[179426550];

    memset(is_prime, 0, sizeof(bool) * 179426550);

    /*for(i=5;i<=limit;i++){
      is_prime[i]=false;
      }*/
    int N=sqrt(limit);
    for(x=1;x<=N;x++){
        for(y=1;y<=N;y++){
            n=(4*x*x) + (y*y);
            if((n<=limit) &&(n%12 == 1 || n%12==5))
                is_prime[n]^=true;
            n=(3*x*x) + (y*y);
            if((n<=limit) && (n%12 == 7))
                is_prime[n]^=true;
            n=(3*x*x) - (y*y);
            if((x>y) && (n<=limit) && (n%12 == 11))
                is_prime[n]^=true;
        }
    }
    for(n=5;n<=N;n++){
        if(is_prime[n]){
            m=n*n;
            for(k=m;k<=limit;k+=m)
                is_prime[k]=false;

        }
    }
    printf("2   3   ");
    for(n=5;n<=limit;n++){
        if(is_prime[n])
            printf("%d   ",n);
    }
    delete []is_prime;
    return 0;
}

Now,I wonder,none is able to output 1 million primes in 1 sec.

One approach could be:

     I store the values in Array but the program size is limited.

Could someone suggest me some way to get first 1 million primes in less

than a sec satisfying the constraints(discussed above) ?

Thanx !!

Jim Balter
  • 16,163
  • 3
  • 43
  • 66
vijay
  • 2,034
  • 3
  • 19
  • 38
  • 2
    Even if you don't generate them, it's likely your terminal won't print 1 million lines in under a second. – Wooble Jun 14 '12 at 19:44
  • 2
    can it be probabilistic? Also `less then a second` is the dependent on the underlying hardware, you can have a really good algorithm on old hardware be slower then a bad algorithm on new hardware. – Samy Vilar Jun 14 '12 at 19:45
  • Also do you mean `find` the first 1 million primes, causes I don't think you will be able to print them, the print buffers is quite small, being IO it takes some time. – Samy Vilar Jun 14 '12 at 19:53
  • @wobble im outputting in a file...using time ./a.out > eratos.txt – vijay Jun 14 '12 at 19:56
  • @samy.vilar then u saying it aint possible or something ?? so can we say that no better algos than sieve available?? btw i do have dual intel core i5 64bit :D – vijay Jun 14 '12 at 19:58
  • Check out http://en.wikipedia.org/wiki/Prime-counting_function the millionth prime is between 10**7 and 10**8 – Samy Vilar Jun 14 '12 at 19:59
  • ya..thnx..I got it @samy.vilar – vijay Jun 14 '12 at 20:05
  • no problem, RSA/DSA and most encryption algorithms that need to find and verify really large primes 2048 bits use probabilistic tests ... check out my answer the algorithm isn't that hard, I've implemented in python. – Samy Vilar Jun 14 '12 at 20:08
  • 1
    It is absolutely unclear whether you achieved your goal and if so, how. The advice in your accepted answer can only give you a double speedup, but you need 8x. Please update your question. What was it that solved it for you, the block output suggested by starbolin? – Will Ness Jun 19 '12 at 16:28
  • For 1 million ,the above approaches are working fine.I was mistaken with 1 millionth number by 10 millionth number.Moreover,I also obtained another method "reusing array of certain size e.g.10,000 again and again.It's pretty fast even for 10 millionth number.Thanx. – vijay Jun 19 '12 at 16:51
  • And now the millionth prime is obtained 0.8 seconds(nearly) using above approaches. – vijay Jun 19 '12 at 16:53
  • @starblue its not competition question bro.But required in alot of programs as you know primes are really very useful. – vijay Jul 05 '12 at 09:17
  • Check out wheel factorization with 2, 3 and 5. Then you have 8 candidates for primes in every 30 numbers, so you can store their flags as a byte. It sped up my sieve by a factor of 3 (20s for numbers up to 1 billion). – starblue Jul 05 '12 at 09:39

4 Answers4

4

Try

int main()
{
    std::ifstream  primes("Filecontaining1MillionPrimes.txt");
    std::cout << primes.rdbuf();
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
2

You've counted the primes incorrectly. The millionth prime is 15485863, which is a lot smaller than you suggest.

You can speed your program and save space by eliminating even numbers from your sieve.

user448810
  • 17,381
  • 4
  • 34
  • 59
0

The fastest way I know to check if a number is prime is to check for compositeness, I've implemented the http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test with great sucess for RSA, it is probabilistic, with high degree of success depending on how many times you run it.

Samy Vilar
  • 10,800
  • 2
  • 39
  • 34
-1

Step 1. don't do a printf

Step 2. buy a faster computer.

NotMe
  • 87,343
  • 27
  • 171
  • 245
  • 1
    Printf is incredibly slow... every time you call the function, it has to scan the format-string, one-character at a time, looking for % symbols, interpreting any format-specifiers, widths, etc. Printf is powerful, but SLOW. – abelenky Jun 14 '12 at 20:01
  • what i learnt is that printf is faster than cout..May b Im mistaken..Newyz thnx :) – vijay Jun 14 '12 at 20:06
  • cout also has to deal with extensive formatting and options. For a fast function, look at puts(). It just puts out a string. No options, no logic, etc... just dump a string until it hits NULL. About as simple (and fast) as you can easily get. – abelenky Jun 14 '12 at 20:10
  • Any call to I/O is going to give time over to the OS, enable a task switch and/or cause the kernel to switch contexts. The I/O calls are going to dominate your run times. Don't output at every prime, save them in an array and move them to a print buffer or write stream in chunks. – starbolin Jun 14 '12 at 20:35