Prime Distance poj 2689 區間內的素數打表模板
阿新 • • 發佈:2019-01-22
#include<iostream> #include<cstdio> #include<cstring> #include<math.h> using namespace std; #define M 1000005 #define N 1 << 17 int l, u; bool is[N];//大範圍的判斷素數 long long prm[N];//大範圍的素數打表 int n; bool ans[M];//判斷區間內那些是素數 int prime[M];//把區間內素數記錄下來 int num;//記錄區間內的素數個數 int primed(int n) { int i, j, k = 0; int s, e = (int) (sqrt(0.0 + n) + 1); memset(is, 1, sizeof(is)); prm[k++] = 2; is[0] = is[1] = 0; for (i = 3; i < e; i += 2) if (is[i]) { prm[k++] = i; for (s = i * 2, j = i * i; j < n; j += s) is[j] = 0; } for (; i < n; i += 2) if (is[i]) prm[k++] = i; return k; } int main() { n = primed(1<<16);//記錄共有多少個素數 while(scanf("%d%d",&l,&u)!=EOF) { for (int i = 0; i < u - l + 1; i++) ans[i] = true; if (l == 1) ans[0] = false; num = 0; /* for(int i=0; i<10; i++) { printf("prm %d\n",prm[i]); }*/ for (int i = 0; i < n && prm[i] * prm[i] <= u; i++) { long long temp = (l + prm[i] - 1) / prm[i] * prm[i]; /* if(i==0) { printf("a%lld b%lld c%lld %lld\n",temp,l + prm[i]- 1,prm[i],prm[i]*prm[i]); }*/ if (temp == prm[i]) temp += prm[i]; while (temp <= u) { ans[temp - l] = false; temp += prm[i]; } } /* for(int i=0; i<u-l+1; i++) { printf("%d\n",ans[i]); }*/ for (int i = 0; i < u - l + 1; i++) if (ans[i]) prime[num++] = l + i; // for(int i=0; i<num; i++) //printf("pppppppppp %d\n",prime[i]); if (num < 2) { printf("There are no adjacent primes.\n"); } else { int ans1 = 0, ans2 = 0; for (int i = 0; i < num - 1; i++) { if (prime[ans1 + 1] - prime[ans1] > prime[i + 1] - prime[i]) ans1 = i; if (prime[ans2 + 1] - prime[ans2] < prime[i + 1] - prime[i]) ans2 = i; } printf("%d,%d are closest, %d,%d are most distant.\n", prime[ans1], prime[ans1 + 1], prime[ans2], prime[ans2 + 1]); } } return 0; }