Differences between revisions 2 and 3
Revision 2 as of 2009-12-25 07:18:56
Size: 1264
Editor: localhost
Comment: converted to 1.6 markup
Revision 3 as of 2010-06-02 03:17:39
Size: 1404
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 20: Line 20:
# 优化::N > 10000 时可以使用 xrange() 进行优化生成数列
# SOP 式的排版:
[ p for p in range(2, N)
    if 0 not in [ p%d
        for d in range(2, int(sqrt(p))+1)
                ]
]
Line 21: Line 28:
# 优化::N > 10000 时可以使用 xrange() 进行优化生成数列
  • 单行程序 扫描素数!

    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() 进行优化生成数列
    # SOP 式的排版:
    [ p for p in range(2, N) 
        if 0 not in [ p%d 
            for d in range(2, int(sqrt(p))+1)
                    ] 
    ]
  • AlbertLee 推荐 ASPN 片段代码讨论

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