hdu 3823 线性筛法

筛出足够多的素数然后存起来查找即可。

 1 #include <algorithm>

 2 #include <iostream>

 3 #include <cstring>

 4 #include <cstdio>

 5 using namespace std;

 6 

 7 typedef long long ll;

 8 const int N = 20000001;

 9 const int M = 1500000;

10 const int K = 150;

11 const int L = 200000;

12 bool visit[N];

13 int prime[M];

14 int ss[K][L];

15 int pm[K];

16 int pn;

17 

18 void better_get_prime()

19 {

20     pn = 0;

21     memset( visit, 0, sizeof(visit) );

22     visit[0] = visit[1] = 1;

23     for ( int i = 2; i < N; i++ )

24     {

25         if ( !visit[i] ) prime[pn++] = i;

26         for ( int j = 0; j < pn && ( ll ) i * prime[j] < N; j++ )

27         {

28             visit[i * prime[j]] = 1;

29             if ( i % prime[j] == 0 ) break;

30         }

31     }

32     memset( pm, 0, sizeof(pm) );

33     for ( int i = 0; i < pn - 1; i++ )

34     {

35         int d = prime[i + 1] - prime[i];

36         if ( d < K )

37         {

38             ss[d][pm[d]++] = prime[i];

39         }

40     }

41 }

42 

43 int main ()

44 {

45     better_get_prime();

46     int t;

47     scanf("%d", &t);

48     for ( int _case = 1; _case <= t; _case++ )

49     {

50         int x, y;

51         scanf("%d%d", &x, &y);

52         if ( x > y ) swap( x, y );

53         int d = y - x, ans = -1;

54         for ( int i = 0; i < pm[d]; i++ )

55         {

56             if ( ss[d][i] >= x )

57             {

58                 ans = ss[d][i] - x;

59                 break;

60             }

61         }

62         printf("Case %d: %d\n", _case, ans);

63 

64     }

65     return 0;

66 }

 

你可能感兴趣的:(HDU)