spoj.com prime generator time limit exceeded

前端 未结 1 1792
死守一世寂寞
死守一世寂寞 2021-01-29 13:04

Getting time limit exceeded on submitting answer. I am also facing same problem with 2-3 more questions that I have submitted on spoj.com.

http://www.spoj.com/problems/

1条回答
  •  被撕碎了的回忆
    2021-01-29 13:57

    Your algorithm is O((m-n)*n) which of course won't run within the allocated time limit. Let's go over your code:

    count=0;
    for(k=1;k<=j/2;k++)
    {
    if(j%k==0)
    count++;
    if(count>1)
    break;
    }
    if(count==1)
    printf("%lld\n",j);
    

    Micro optimization: Why do you need a counter? You could get away with a bool.

    Optimization: Why are you testing primes j/2? If j has a divisor greater than 1 than it's guaranteed that j has a divisor that's at most sqrt(j).

    Micro Optimization: Don't consider even numbers at all, except for 2.

    bool prime = j==2 || j%2==1 ;
    for(k=2;prime && k*k<=j;k++)
    {
    if(j%k==0) prime = false;
    }
    }
    if(prime) printf("%lld\n",j);
    

    Now this is O((m-n)*sqrt(n)) which is a lot faster.

    I suppose this won't make the limit. You could extend the second micro-optimization to skip numbers divisible by 3 very easy.

    Optimization: If this is still not enough then you have to do a pseudo-primality test. One test that's very easy to implement in O(log(n)) is https://en.wikipedia.org/wiki/Fermat_primality_test. With this the complexity is down to O((m-n)*log(n)) which should be run in the available time limit.

    0 讨论(0)
提交回复
热议问题