I've implemented a simple program that finds all prime numbers between two integer inputs using Sieve of Eratosthenes, but online judge is still complaining that time limit is exceeding. Maybe I'm doing something wrong, but how can I optimize (or debug if necessary) my code?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t;
unsigned int i, j, k;
cin >> t;
int m, n;
cin >> m >> n;
if (n - m <= 100000 && m <= n && 1 <= m && n <= 1000000000)
{
int a[n - m + 1];
for (j = 0; j < n - m + 1; ++j)
{
a[j] = m + j;
}
for (j = 2; j <= sqrt (n); ++j)
{
for (k = 0; k < n - m + 1; ++k)
{
if (a[k] % j == 0 && a[k] != 0)
{
break;
}
}
for (; k < n - m + 1; k = k + j)
{
if (a[k] != j)
{
a[k] = 0;
}
}
}
if (a[0] == 1)
{
a[0] = 0;
}
for (j = 0; j < n - m + 1; ++j)
{
if (a[j])
{
cout << a[j] << endl;
}
}
cout << endl;
}
return 0;
}
Thanks in advance