zoukankan      html  css  js  c++  java
  • Python练习题 030:Project Euler 002:偶数斐波那契数之和

    本题来自 Project Euler 第2题:https://projecteuler.net/problem=2

    # Each new term in the Fibonacci sequence is generated
    # by adding the previous two terms.
    # By starting with 1 and 2, the first 10 terms will be:
    # 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
    # By considering the terms in the Fibonacci sequence
    # whose values do not exceed four million,
    # find the sum of the even-valued terms.
    # Answer: 4613732
    
    sum = 0
    a, b = 0, 1
    while b < 4000000:
        if b%2 == 0:
            sum += b
        a, b = b, a+b
    print(sum)
    

    可能学计算机或数学的人都很喜欢 Fibonacci 吧,甚至有文章把这个 斐波那契数列 称为自然界神之存在,真是……

    类似的题目已经做过很多次了。简单地说,因为这个数列中的任意数字(第1、2个除外),都是前两个数字之和,所以先初始化第1、2个数字 a, b = 0, 1。用一个 while 循环来判断:每次只判断 b 是否为偶数(即是否可以被2整除),是的话,就加入 sum 里,然后把 b 赋值给 a,而 b 的新值是 a+b,即通过 a+b 确定下一个斐波那契数字,直到 b 超出 4000000 的限值为止。

    a, b = b, a+b 这样的写法真是太方便了!根本不需要考虑 b 赋值给 a 后,对 a+b 会有什么样的影响。

  • 相关阅读:
    CSUFT 1002 Robot Navigation
    CSUFT 1003 All Your Base
    Uva 1599 最佳路径
    Uva 10129 单词
    欧拉回路
    Uva 10305 给任务排序
    uva 816 Abbott的复仇
    Uva 1103 古代象形文字
    Uva 10118 免费糖果
    Uva 725 除法
  • 原文地址:https://www.cnblogs.com/iderek/p/6007774.html
Copyright © 2011-2022 走看看