Yes, Prime Minister
参考
# include <iostream>
# include <cstdio>
# include <string>
# include <cmath>
# include <cstring>
# include <algorithm>
# include <map>
# include <vector>
using namespace std;
# define ll long long
# define lowbit ( x) x& - x
typedef pair< int , int > pll;
const int mod= 1e9 + 7 ;
double pi= acos ( - 1 ) ;
const int N = 4e7 + 5 ;
int vis[ N] , p[ N] , p1[ N] ;
void init ( ) {
vis[ 0 ] = vis[ 1 ] = 1 ;
int i, j;
for ( i = 2 ; i < N; i++ ) {
if ( ! vis[ i] ) p[ ++ p[ 0 ] ] = i;
for ( j = 1 ; j <= p[ 0 ] ; j++ ) {
if ( i * p[ j] >= N) break ;
vis[ i * p[ j] ] = 1 ;
if ( i % p[ j] == 0 ) break ;
}
}
for ( i = 1 ; i <= 20000001 ; i++ ) {
if ( vis[ 2 * i + 1 ] == 0 ) p1[ ++ p1[ 0 ] ] = i;
}
}
bool ok ( int x) { return vis[ x] == 0 ; }
int solve ( int x) {
int ans = - 1 ;
if ( x > 0 ) {
if ( x == 1 ) return 2 ;
if ( ok ( x) ) return 1 ;
if ( ok ( x + x + 1 ) ) return 2 ;
if ( ok ( x + x - 1 ) ) return 2 ;
ans = 2 * x + 1 ;
x = x + 1 ;
int a1 = p[ lower_bound ( p + 1 , p + 1 + p[ 0 ] , x) - p] ;
int a2 = p1[ lower_bound ( p1 + 1 , p1 + 1 + p1[ 0 ] , x) - p1] ;
if ( a1 <= a2)
ans = ans + 2 * ( a1 - x) + 1 ;
else
ans = ans + 2 * ( a2 - x) + 2 ;
} else if ( x == 0 )
return 3 ;
else {
x = - x;
ans = 2 * x + 1 ;
x = x + 1 ;
int a1 = p[ lower_bound ( p + 1 , p + 1 + p[ 0 ] , x) - p] ;
int a2 = p1[ lower_bound ( p1 + 1 , p1 + 1 + p1[ 0 ] , x) - p1] ;
if ( a1 <= a2)
ans = ans + 2 * ( a1 - x) + 1 ;
else
ans = ans + 2 * ( a2 - x) + 2 ;
}
return ans;
}
signed main ( ) {
init ( ) ;
int T, x;
cin >> T;
while ( T-- ) {
cin >> x;
cout << solve ( x) << endl;
}
}