Help me in solving FREEQ problem

My issue

Time Limit Exceeding !

My code

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define N 1e6

vector<bool> prime;

void sieve(int n) {
    prime = vector<bool> (n+1,true);
    
    for (int p=2;p*p<=n;++p) {
        if (prime[p]==true) {
            for (int i=p*p;i<=n;i+=p) prime[i]=false;
        }
        
    }
}

signed main() {
	// your code goes here
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        sieve(N);
        
        if (n==1) { cout << 1 << endl; continue; }
        else if (n%2==1) { cout << 1<<" "; --n; }
        
        
        n/=2;
        for (int i=2;i<N;i++) {
            if (prime[i]==false) continue;
            { cout << i << " "<<i<<" "; n--; }
            if (n==0) break;
        }
        cout << endl;
    }
}

Problem Link: Frequal Practice Coding Problem - CodeChef

@abhinav_singh1
U have to call the sieve function outside the test case loop.

1 Like