python学习习题总结(3)——菲波那切数列,求10万以内素数优化

#斐波那契数列,a,b = b,a+b
first = 0
second = 1
cnt = 2
for i in range(101-2):
    mid = first + second
    cnt += 1
    first = second
    second = mid
print(mid)


zero = 0
one = 1
cont = 2
for i in range(101-2):
    one = zero + one
    cont += 1
    zero = one - zero
print(one)


a = 0
b = 1
co = 2
for i in range(101-2):
    a,b = b,a+b
    co += 1

print(b)

#素数

#求10万以内所有的素数,优化,筛法

ceil(sqrt)开方后向上取整,一个数分解质因数,开方是中间位置

计算放到循环外面,跳步,判断和赋值效率最高

筛法只用到判断和赋值

#列表+孪生素数

import math
import datetime
n = 100000
begin = datetime.datetime.now()
lst = [2,3]
foo = 5
step = 2
while True:
    point = math.ceil(math.sqrt(foo))
    for i in lst:
        if not foo % i:
            break
        if i >= point:
            lst.append(foo)
            break
    foo += step
    if foo > n:
        break
    step = 4 if step == 2 else 2
delta = (datetime.datetime.now()-begin).total_seconds()
print(delta)
print(len(lst))
print('-'*50)
#筛法
begin = datetime.datetime.now()
supPrimes = [True]*(n+1)
supPrimes[0] = False
supPrimes[1] = False
point = math.ceil(math.sqrt(n))
for i in range(2,point):
    if not supPrimes[i]:
        continue
    else:
        for j in range(i*i,n+1,i):
            supPrimes[j] = False
primes = [i for i in range(n+1) if supPrimes[i]]
delta = (datetime.datetime.now()-begin).total_seconds()
print(delta)
print(len(primes))

猜你喜欢

转载自blog.csdn.net/qq_33287645/article/details/79684684