Every prime number greater than 3 is of the form 6n+1 or 6n-1. The converse is not true. Use sieve of Eratosthenes or just modify your code a bit.

Add a check prime function. We assume that n > 3.

```
bool isPrime(int n)
{
bool flag = 1;
for (int i = 2; i*i <= n; ++i)
{
if (n % i == 0)
{
flag = 0;
break;
}
}
return flag;
}
set <int> prime;
prime.insert(2);
prime.insert(3);
for(int i = 6; i < 1e6 + 7; i+=6)
{
if (isPrime(i-1)) prime.insert(i - 1);
if (isPrime(i+1)) prime.insert(i + 1);
}
```

The complexity will be O(n(\sqrt{n}+\log{n})) because `isPrime()`

is O(\sqrt{n}) and insertion in a set takes O(\log{n}) but sieve of Eratosthenes is only O(n\log{(\log{n})}) which is much more fast.

I’d suggest using sieve rather than this approach (or remove the set and use a vector with `push_back()`

).