1 / 2
May 2021

//Why this code shows time limit excedded , while it runs in less than a second in codeblocks
#include
using namespace std;

bool CheckPrime(long int p)
{
for(long int i=2 ; i<= (p/2) ; i++ )
{
if(p%i !=0 ) continue;
else return false;
}
return true;
}

int main()
{
long int t;
cin>>t;
long int m[t],n[t]; // making array for reading the i th value of m and n initially , and working on prime afterwards on whole set.
for (long int k=1; k<=t; k++)
{
cin>>m[k]>>n[k];
}
for (long int k=1; k<=t; k++) //repeating the whole process t times.
{

    for (long int i = m[k] ; i<=n[k]; i++)
    {
        if (i == 1)  continue; //as 1 is not a prime number but this function CheckPrime will return true for it anyway.
        else
        {
            if(CheckPrime(i)) cout<<i<<endl;

        }
    }
    if(! CheckPrime( n[t-1] ) ) // arrays are stored in 0 ht to t-1 th elememnt. Earlier I was writing here n[t], which didn't lay any gap between two t values.
        cout <<endl;

}

return 0;

}

  • created

    May '21
  • last reply

    May '21
  • 1

    reply

  • 523

    views

  • 2

    users

It runs in less than a second but for what test cases? You have no idea what test cases are given to it by the SPOJ judge.

Search this forum for ideas–questions about this problem have been asked many times before.