当前位置:   article > 正文

欧拉筛(又称线性筛)_ola筛

ola筛

清楚明白的博客!

其中ola筛就是少了很多重复,必须理解 if(n % primes[j])break; 是因为什么!(数学逻辑推理证明了能够减少多次重复筛选)

例题:

https://ac.nowcoder.com/acm/contest/21753/J

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. const int N = 1e7+10;
  5. int st[N];
  6. int primes[N], cnt;
  7. void ola()
  8. {
  9. st[1] = 1;
  10. for (int i = 2; i <= N; i++)
  11. {
  12. if (!st[i])
  13. primes[cnt++] = i;
  14. for (int j = 0; primes[j] * i <= N; j++)
  15. {
  16. st[primes[j] * i] = 1;
  17. if (i % primes[j] == 0)
  18. break;
  19. }
  20. }
  21. }
  22. int a[N];
  23. int main()
  24. {
  25. ola();
  26. int n;
  27. scanf("%d", &n);
  28. int ans = 0;
  29. int x;
  30. while (n--)
  31. {
  32. scanf("%d", &x);
  33. if (!st[x])
  34. {
  35. a[ans++] = x;
  36. }
  37. }
  38. printf("%d\n", ans);
  39. if (!ans)
  40. {
  41. printf("-1");
  42. return 0;
  43. }
  44. sort(a, a + ans);
  45. for (int i = 0; i < ans; i++)
  46. {
  47. printf("%d ", a[i]);
  48. }
  49. }

几个需要注意的坑点:

1、st初始化似乎不能在外面?(int st[N]={1,1}会提示你编译错误)

2、N赋值的时候必须+10或+5,否则会出现很傻的边界debug问题

3、对于卡的时间紧的题目,必须scanf和printf!(这道题如果不用这两个就TLE了)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/947520?site
推荐阅读
相关标签
  

闽ICP备14008679号