直接打表素数后查找即可。
1 #include<cstdio> 2 #include<cstring> 3 #include<cctype> 4 #include<cstdlib> 5 #include<cmath> 6 #include<iostream> 7 #include<sstream> 8 #include<iterator> 9 #include<algorithm> 10 #include<string> 11 #include<vector> 12 #include<set> 13 #include<map> 14 #include<queue> 15 #include<stack> 16 #include<list> 17 #include<ctime> 18 #define Memset(x) memset(x, 0, sizeof(x)) 19 #define all(x) x.begin(), x.end() 20 const int E = 2000000 + 10; 21 const double EPS = 1e-6; 22 using namespace std; 23 24 typedef unsigned long long llu; 25 vector<int> prime; 26 int pri[E]; 27 28 void dabiao(){ 29 pri[0] = 1, pri[1] = 1, pri[2] = 0; 30 int len = 0; 31 for(int i = 2; i < E; i++){ 32 if(len > 100000) break; 33 if(!pri[i]){ 34 prime.push_back(i); len++; 35 for(int j = i * 2; j < E; j += i) 36 pri[j] = 1; 37 } 38 } 39 } 40 41 int main(){ 42 Memset(pri); 43 dabiao(); 44 int n; 45 while(scanf("%d", &n) == 1 && n){ 46 if(!pri[n]) {printf("0\n"); continue;} 47 vector<int>::iterator temp = upper_bound(all(prime), n); 48 printf("%d\n", *temp - *(temp - 1)); 49 } 50 return 0; 51 }