Algorithm Gossip (15) 筛选求质数(Eratosthenes )
来源:互联网 发布:nginx rtmp hls 编辑:程序博客网 时间:2024/05/29 18:03
前言
This Series aritcles are all based on the book 《经典算法大全》; 对于该书的所有案例进行一个探究和拓展,并且用python和C++进行实现; 目的是熟悉常用算法过程中的技巧和逻辑拓展。
提出问题
15.Algorithm Gossip: 筛选求质数(Eratosthenes )
说明
除了自身之外,无法被其它整数整除的数称之为质数.
筛选原理
逐步选出小质数对应的集合元素, 直到筛选质数到 sqrt(N)。
分析和解释
计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:
首先,列出从2开始的所有自然数,构造一个序列:
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:
5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
取新序列的第一个数5,然后用5把序列的5的倍数筛掉:
7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, …
不断筛下去,就可以得到所有的素数。
用Python来实现这个算法,可以先构造一个从3开始的奇数序列:
代码
C语言有待改进的示例
#include <stdio.h>#include <stdlib.h>#define N 1000int main(void) { int i, j; int prime[N+1]; for(i = 2; i <= N;i++) prime[i] = 1; for(i = 2; i*i <= N;i++) { if(prime[i] == 1) { for(j = 2*i; j <= N;j++) { if(j % i == 0) prime[j] = 0; } } } for(i = 2; i < N;i++) { if(prime[i] == 1) { printf("%4d ", i); if(i % 16 == 0) printf("\n"); } } printf("\n"); return 0; }
python 的 fitter 实现
def _odd_iter(): n = 1 while True: n = n + 2 yield n# 筛选函数def _not_divisible(n): return lambda x: x % n > 0#生成器, 不断返回素数def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列##主函数for n in primes(): if n < 1000: print(n) else: break
PS, 对 fitter , yied 不熟悉的可以百度了解下生成器和迭代器。
yied 主要用于不断生成目标返回到元组的一种append方式 -> 生成器, fitter 为删选机制。
拓展和关联
后记
参考书籍
- 《经典算法大全》
- 维基百科
- Algorithm Gossip (15) 筛选求质数(Eratosthenes )
- Algorithm Gossip: Eratosthenes筛选求质数
- Algorithm Gossip: 筛选求质数
- Eratosthenes筛选求质数
- 14 Eratosthenes 筛选求质数
- Eratosthenes筛选法计算质数
- 质数筛选(详细解释以及模板)(Eratosthenes)
- (7)筛选求质数
- Sieve of Eratosthenes求质数
- 找质数算法之埃拉托色尼筛选法(Sieve of Eratosthenes算法)
- 筛选法求质数(素数)
- 求质数:筛选法(埃拉托色尼筛法)
- 筛选法求质数(acm)
- 筛选求质数
- 筛选法求质数
- Eratosthenes筛选法求素数的算法
- Eratosthenes筛选法求素数的算法
- 第六章课后题:质数Eratosthenes筛选法
- titanic版本二代码注释
- spring转发和重定向
- Leetcode 127(Java)
- [BZOJ3706]反色刷(并查集+欧拉图)
- SpringMVC最小demo创建
- Algorithm Gossip (15) 筛选求质数(Eratosthenes )
- java 线程池的个人记录
- 飞机大战
- Javaの值传递和引用传递
- linux之守护进程与操作编程
- AtCoder 2286 C
- 20174-13练习
- 如何判断微信内置浏览器(JS & .Net)
- 【线段树】 求区间最小值以及区间最小值