i tried to solve SPOJ prime number problem. the code produced correct result, but Time limit exceeded and also memory need around 970M which is not efficient(?)
what makes my code slow and how can i optimize this code under time constraint around few seconds? thanks!
problem:
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.
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include <cmath>
#include <vector>
#include<iostream>
using namespace std;
void simplesieve(int limit, vector<int>&prime);
void segmentedsieve() {
int T, M, K;
cin >> T;
for (int t = 0; t < T; t++) {
cin >> M >> K;
const int limit = floor(sqrt(K)) + 1;
vector<int> prime;
simplesieve(K, prime);
bool *mark = new bool[K - M];
memset(mark, true, sizeof(bool)*(K-M));
vector<int>::iterator it;
for (it = prime.begin(); *it<limit; it++) {
int lolim = floor(M / (*it))*(*it);
if (lolim < M)
lolim = lolim + (*it);
for (int j = lolim; j < K; j += (*it))
{ if(j!=*it)
mark[j - M] = false;
}
}
for (int i = M; i < K; i++) {
if (mark[i - M] == true)
cout << i << "\n";
}
delete[] mark;
}
}
constexpr int n(int limit) {
return limit;
}
void simplesieve( int limit, vector<int>&prime) {
bool *mark=new bool[limit + 1];
memset(mark, true, sizeof(bool)*(limit+1));
for (int p = 2; p*p < limit; p++) {
if (mark[p] == true) {
for (int i = p * 2; i < limit; i += p)
mark[i] = false;
}
}
for (int p = 2; p < limit; p++) {
if (mark[p] == true)
{
prime.push_back(p);
}
}
}
int main()
{
int n = 100;
segmentedsieve();
return 0;
}