【发布时间】:2013-01-03 21:27:51
【问题描述】:
可能重复:
Find out 20th, 30th, nth prime number. (I’m getting 20th but not 30th?) [Python]
Fastest way to list all primes below N in python
质数:
P=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, …]
斐波那契数:
F=[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …]
我希望用户给出一个介于 (1,100000) 和程序之间的随机数来总结结果 (F[n]+P[n])for example if n=3 F[3]+P[3]=7+2=9
我写了以下代码:
import math
def F(n):
return int(((1+math.sqrt(5))**n-(1-math.sqrt(5))**n)/(2**n*math.sqrt(5)))
L=[]
L.append(2)
L=[]
for n in range(2, 10000):
for x in range(2, n):
if n % x == 0:
break
else:
# loop fell through without finding a factor
L.append(n)
while True:
x = raw_input().strip()
if x == "END" or x == "end":
break
else:
num = int(x)
print F(num)+L[num]
我很容易从 def F(n) 中找到 Fib 数字,但是创建素数列表确实是一个令人头疼的原因,因为随着数字的增加,创建列表需要一些时间,并且几乎不可能达到 n 成那些巨大的数字..我试图做一个 def 不创建列表,而只是为用户提供的 n 计算素数。有什么想法吗??
提前致谢!
【问题讨论】:
-
这个问题基本上归结为stackoverflow.com/questions/1995890/…
-
生成素数的算法比计算机还要古老。你做过研究吗?
-
使用Sieve of Eratosthenes 获取素数列表。这是一个非常快速且易于实现的算法。