http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1030
用线性筛素数果然快多了。
#include<cstdio> #include<cstring> #include<cstdlib> #define MAXN 1300000 bool is_p[MAXN]; void calc() { for( int i = 1; i < MAXN; i ++) is_p[i] = true; is_p[1] = false; for( int i = 2; i < MAXN; i ++) { if( !is_p[i]) continue; for( int j = 2; i * j < MAXN; j ++) is_p[i * j] = false; } } int main() { int n, k, cnt; calc(); scanf( "%d", &n); while( n --) { scanf( "%d", &k); cnt = 0; for( int i = k; !is_p[i]; i ++) cnt ++; for( int i = k; !is_p[i]; i --) cnt ++; printf( "%d\n", cnt); } return 0; }