Differences between revisions 1 and 4 (spanning 3 versions)
 ⇤ ← Revision 1 as of 2007-03-22 11:51:01 → Size: 1262 Editor: ZoomQuiet Comment: ← Revision 4 as of 2010-06-02 03:18:06 → ⇥ Size: 1418 Editor: ZoomQuiet Comment: Deletions are marked like this. Additions are marked like this. Line 20: Line 20: Line 23: Line 22: * AlbertLee 推荐 [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162479 ASPN 片段代码讨论] {{{#!python# SOP 式的排版:[ p for p in range(2, N)     if 0 not in [ p%d         for d in range(2, int(sqrt(p))+1)                ] ]}}} * AlbertLee 推荐 [[http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162479|ASPN 片段代码讨论]]
• 单行程序 扫描素数!

```from math import sqrt
# 求N 以内的素数...
from math import sqrt
N = 100
[ p for p in   range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]
^ ^  ^     ^               ^    ^      ^  ^              ^            ^      ^
| |  |     |               |    |      |  |              |            |      +- 弥补
| |  |     |               |    |      |  |              |            +- 通过平方精简尝试
| |  |     |               |    |      |  |              +- 组织所有 2~p 之间可能为公因子的数列
| |  |     |               |    |      |  +- 求余,尝试整除
| |  |     |               |    |      +- 列表运算,直接将以上计算结果组成数组 返回
| |  |     |               |    +- 余数0 不在求余结果列表中
| |  |     |               +- 即2~p 都不能整除 p 的p
| |  |     +- 提取运算
| |  +- for..in 循环取数,从2~p 的连续数组中
| +- 素数!
+- 列表计算组织所有结果为数组返回!
# 优化::N > 10000 时可以使用 xrange() 进行优化生成数列```

```   1 # SOP 式的排版:
2 [ p for p in range(2, N)
3     if 0 not in [ p%d
4         for d in range(2, int(sqrt(p))+1)
5                 ]
6 ]
```

PyPrimeNumberGenerator (last edited 2010-06-02 03:18:06 by ZoomQuiet)

• getACL = 0.017s
• init = 0.000s