简体   繁体   中英

How can I avoid TLE on SPOJ with this prime number generator program?

This is the Prime Number generator program on SPOJ. I am facing the dreaded "Time Limit Exceeded" error. How can I overcome it? This is the link to the problem:- https://www.spoj.com/problems/PRIME1/

What could be the reason? I am still a beginner and I searched on net and it's telling me to use some algorithms, but right now I don't know any algorithms.

#include <stdio.h>

void prime(int a,int b)
{
    int y=0;
    for (int i=a;i<=b;i++)
    {
        for (int j=2;j<i;j++)
        {
            int x=i%j;
            if (x==0)
            {
                break;
            }
            else
            {
                y++;
            }
        }
        if (y==i-2)
        {
            printf("%d\n",i);
        }
        y=0;
    }
}

int main()
{
    int test;
    int arr1[11],arr2[11];
    char space[11];
    scanf("%d",&test);

    if (test>10)
    {
        goto end;
    }

    for (int i=0;i<test;i++)
    {
        scanf("%d%c%d",&arr1[i],&space[i],&arr2[i]);
        if (arr1[i]>=1 && arr1[i]<=arr2[i] && arr2[i]<=1000000000 && arr2[i]-arr1[i]<=100000 && space[i]==' ')
        {
            prime(arr1[i],arr2[i]);
            printf("\n");
        }
    }
    printf("\n");
end:
    return 0;
}

Here is the code to check if a number if prime. It's complexity is O(sqrt(N)). The O(N*sqrt(N)) proposed solution passes all test cases as nm <= 100000.

 bool checkprime(int x){
        if(x==1)
            return false;
        if(x<=3)
            return true;
        for(int i=2;i<=sqrt(x);i++){
            if(x%i==0)
                return false;
        }
        return true;
    }

Some pseudo code to call and check if a number is prime.

for(int i=l;i<=r;i++){
    if(checkprime(i))
        cout<<i<<endl;
    else
        continue;
 }

However the Segmented Sieve of Eratosthenes method works much faster and is a better method to answer all the queries.

Your solution seems to be quadratic, which will time out for large numbers. To make it more efficient, you can try a different method such as the Sieve of Eratosthenes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM