作者Lucemia (生の直感、死の予感)
看板Python
标题Re: [问题] 用Python算质数
时间Fri Apr 24 07:38:24 2009
※ 引述《leondemon (狗狗)》之铭言:
: 改自http://larc.ee.nthu.edu.tw/~jcyeh/python/cdoc/tut/node6.html
: code如下:那行
: ===========
: def primeNumber(x):
: for n in xrange(2,x):
: for m in xrange(2,n): #第二个for loop
: if n%m == 0:
: break
: else: #为何else要缩排在这里?
: print n,
: x = int(raw_input("enter a number:"))
: primeNumber(x)
: ===========
: 当数字大於100000时 计算就耗时了
: 有办法改code加速寻找质数的运算吗?
^^^^^^^^
1. 寻找质数无有效的方式 (无多项式时间解)
2. 没有有效的,但有很多种较好的解、
像是筛法、
这个范例写的是直接照质数的定义、
是最不好的解。自然很慢。
但不管怎样改、在大数下都不会快
(如将 xrange(2, n ) 改成 xrange(2, sqrt(n)) 都会好些)
3. for 的 else 与 if 的 else statment 不一样
for 的 else 是拿来处理 break的 (文章内有写)
用途就是只在for break时执行这些步骤、若for 正常执行就不做
下面这种情况较能感觉到这个用法的好处
for ...
if (A): break
....
if (B): break
...
if (C): break
else:
print "For loop break"
: 另外一个问题:else那行如果缩排退一格 结果会变得不同
: 而我不太懂else是针对什麽情况之下发生?
: 因为它是跟for对齐,但是通常不是都跟if放在一起吗?
: break是中断第二个for loop对吧?中断後为何不执行else步骤呢?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 154.20.36.163
1F:推 leondemon:感谢~ 04/24 10:20
2F:推 leondemon:再问另外一个问题 python计算的数字有上限吗? 04/24 11:00
3F:推 Yshuan:关於质数 之前写过MR演算法 搭配100内质数表 听说是最快的 04/24 20:14
4F:推 leondemon:用python写吗? 愿不愿意分享一下code? :) 04/24 22:50
5F:→ leondemon:这篇讲完後 对没资讯背景的我获益良多 :) 感恩 04/25 04:05
6F:→ Holocaust123:L大你的3.讲错了 11/08 06:19