I am solving this prime generator problem from SPOJ:
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
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.
I’m using the Sieve of Eratosthenes. Whenever I submit the following code it gives Time Limit Exceeded. Can anyone please give me some optimizations that can make my code run faster?
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
using ll = long long;
int main() {
ios_base::sync_with_stdio(false);
int t = 0;
cin >> t;
while (t--) {
ll first = 0, n = 0;
cin >> first >> n;
vector<bool> primes(n+1, 0);
for (ll i = 2; i <= sqrt(n); ++i) {
if (primes[i] == 0) {
for (ll j = 2; (i*j) <= n; ++j) {
primes[i*j] = 1;
}
}
}
for (ll i = 2; i <= n; ++i) {
if (primes[i] == 0 && i >= first) {
cout << i << '\n';
}
}
}
return 0;
}
t
is for, but I really don't want to spend any further time trying to figure out what this code is trying to do. \$\endgroup\$vector<bool>
it differs significantly from other containers and is optimized for space not speed. Your code will run much quicker by usingvector<char>
\$\endgroup\$prime
is in the wrong place. By moving it out a level you don't need to re-calculate all the values again and again. \$\endgroup\$