Prime Permutation code failing at 2 test case START100 HELP

  • I’m finding 2 prime numbers which sum to ‘n’. Then printing the permutation such that difference is always one of those 2 selected numbers.
#include <bits/stdc++.h>
using namespace std;
#define f(a,b,n) for(int a=b; a<n; a++)
#define speed                         \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL);
#define mod 1000000007

const int sz = 100001;
bool prime[sz];
vector<int> v= {2};
void find(){
    f(i,2,sz){
        if(i&1){
            int root = floor(sqrt(i));
            bool p = true;
            for(int j=3; j<=root+1; j+=2){
                if(i%j==0){
                    p = prime[i] = false;
                    break;
                }
            }
            if(p){
                prime[i] = true;
                v.push_back(i);   
            }
        }
        else{
            prime[i] = (i==2);
        }
    }
}


void solve(){
    int n; cin>>n;
    bool flag = true;
    for(int i : v){
        if(i>=n){
            break;
        }
        int rem = n-i;
        if(prime[rem]){
            flag = false;
            // cout<<i<<" "<<rem<<endl;
            int j = i+1;
            while(j<=n){
                cout<<(j++)<<" ";
            }
            j = 1;
            while(j<=i){
                cout<<(j++)<<" ";
            }
            cout<<endl;
            break;
        }
    }
    if(flag){
        cout<<-1<<endl;
    }
}


int main(){
    speed;
    int cases;
    cin>>cases;
    find();
    while(cases--){
        solve();
    }
    return 0;
}



You print -1 for n = 11, but there is in fact a valid permutation for that.

1 Like