Differences between revisions 3 and 4
Revision 3 as of 2010-06-02 03:17:39
Size: 1404
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 21: Line 21:
}}}
{{{#!python
Line 27: Line 29:

  • 单行程序 扫描素数!

    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)