Solution not being accepted!

Following is my code for the problem Prime Generator having code PRIME1. The solution not being accepted on codechef saying ‘Time Limit Exceeded’ but the same is being accepted on spoj in 0.94 second.

My code goes here:

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int m, n;
		cin>>m>>n;
		for(int j=m; j<=n; j++)
		{
			int flag=1;
			for(int k=2; k<=sqrt(j); k++)
			{
				if(j%k==0)
				{
					flag=0;
					break;
				}
			}
			if(flag && j!=1)	cout<<j<<endl;
		}		
	}
	return 0;
}

That Q on SPOJ must be the “easy” version of this problem. Here the limits are much higher and hence you need a cleverer approach to tackle it in given time.

Read about sieve of erastothenes and segmented sieve, and then attempt. Also, since output is large, dont use endl; as its slow. Use the newline character for newlines.

//