python学习 算法分析 “偶数累加和”

计算 0~100 中所有偶数的和,两种算法:

算法一

此算法通过 if 筛选出偶数。
whileifi += 1分别执行了 n 次,s += i 执行了 n/2

s = 0
i: int = 0
while i <= 100:
    if i % 2 == 0:
        s += i
    i += 1
print(s)

算法二

此算法直接得到偶数。
whiles += ii += 2 分别执行了 n/2

s = 0
i: int = 0
while i <= 100:
    s += i
    i += 2
print(s)

结论

算法二理论上速度更快

猜你喜欢

转载自blog.csdn.net/wb1511786474/article/details/88398789