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 会有什么样的影响。

  • 相关阅读:
    ubuntu下android开发工作环境搭建
    ADB命令行控制界面开关
    chromium os系统编译与环境搭建
    完整代理的简单实现
    OC协议、代理的简单使用
    OC字典的使用
    OC数组的简单使用、NSArray
    OC中NSString的使用、字符串的使用
    OC内存管理、非ARC机制、MRR机制
    OC中重写set和get方法、懒加载
  • 原文地址:https://www.cnblogs.com/iderek/p/6007774.html
Copyright © 2011-2022 走看看