Given that the inputs can be up to 1000000000, how can I write a more time and memory efficient program? (print all primes between m and n)

◇◆丶佛笑我妖孽 提交于 2020-12-13 09:40:21

问题


Here is the code below (ans to a CP qs)

The time limit for execution is 6 seconds but my code is slower than.

How can I make it more memory and time efficient ?

  • Input: the input begins with the number t of test cases in a single line (t <= 10).

  • In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m <= 100000) separated by a space.

  • Output : for every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    long int t,m,n,i,j,k;
    //printf("Enter number of testcases:\n");
    scanf("%ld",&t);
    long int test[t][2];
    for(i=0;i<t;i++){
        //printf("Enter m,n:\n");
        scanf("%ld %ld",&test[i][0],&test[i][1]);
    }
    
    for(k=0;k<t;k++){    
        for(i=test[k][0];i<=test[k][1];i++){
            for(j=2;j*j<i*i;j++){
                if(i%j==0)
                    break;
            }
            if(j==i){
                printf("%ld\n",i);
                }
            }
            printf("\n");
    }
    return 0;
}

回答1:


Use offset sieve of Eratosthenes (see also this answer, with pseudocode; both links are to SO answers by me).

It is a segmented sieve of Eratosthenes modified to work on only one segment, as per your inputs.

The difference is that a segmented sieve proceeds by segments indefinitely and uses as many of the primes as needed by the segment currently being sieved (up to its top limit's square root); here the top segment's limit (and hence the core segment's) is known upfront.

The core segment extends up to the sqrt of the biggest value to be considered; here it is given to you as 10^9. sqrt(10^9) < 32000, so the core segment spans 0 to 32000, and is sieved by the simple sieve of Eratosthenes.

Since you have several runs, use the same core for each run.

The code in the linked answer is easily amended to this question's requirements: instead of estimating the top value, just use the n supplied to you in the input. above is what's called m here.



来源:https://stackoverflow.com/questions/62484842/given-that-the-inputs-can-be-up-to-1000000000-how-can-i-write-a-more-time-and-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!