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;
}
j
> 2. Test separately for 2 and then start yourj
loop at 3 and step 2 – Latonyat
. Therefore, there is no need to keep all those values, suggest a simple loop, decrementingt
until 0 and the body of the loop only has to work with the latest 2 values read from the input. Also, the functions:scanf()
andprintf()
are VERY CPU intensive. Suggest using:getchar_unlocked()
andputchar_unlocked()
– Basseterretest[][]
over and over and over` is a real time waster. Suggest only working with the two inputs of a single test case at a time – Basseterre1000000000
is well within the limits of aunsigned int
so suggest not usinglong int
– Basseterre10^9
and inserting the results into your 'test' program asstatic const
data. Then the problem solution is a simple: loop through the prime data until one is found that is >= the start value, then output every value encountered until (but not including) the value exceeds the stop value – Basseterrestdlib.h
Suggest that header file be removed – Basseterremath.h
and calculatesqrt(i)
into a separate variable, then using that separate variable similar to:int sqrt_n = sqrt( n ); for( j=3; j<=sqrt_n; j+=2 )
– Basseterre