zoukankan      html  css  js  c++  java
  • Problem 2 : Even Fibonacci numbers

    Problem:

    1. Each new term in the Fibonacci sequence is generated by adding the previous two terms.By starting with1and2, the first 10 terms will be:
    2. 1,2,3,5,8,13,21,34,55,89,...
    3. By considering the terms in the Fibonacci sequence whose values donot exceed four million, find the sum of the even-valued terms.
     
    第二题与斐波那契数列相关,求所有不大于4000000的偶数斐波那契数之和。
     
    逐一求斐波那契数,判断后决定是否累加,代码很简单:
     1 #ProjectEuler promble 2: Even Fibonacci numbers
     2 RANGE = 4000000
     3 prev = 1
     4 cur = 1
     5 sum = 0
     6 while cur <= 4000000:
     7     if cur % 2 == 0:
     8         sum += cur
     9     temp = cur
    10     cur += prev
    11     prev = temp
    12 print(sum)
     
    结束这个问题前,再看看斐波那契数列
    1    1    2    3    5    8    13    21    34    ……
    a    b    c    a    b    c     a     b      c    ……
     
    可见,斐波那契数列偶数项的分布是有规律的,这样可以省略判断是否为偶数的步骤:
     
     1 #ProjectEuler promble 2: Even Fibonacci numbers
     2 RANGE = 4000000
     3 odd1 = 1
     4 odd2 = 1
     5 even = odd1 + odd2
     6 sum = 0
     7 while even <= 4000000:
     8     sum += even
     9     odd1 = odd2 + even
    10     odd2 = even + odd1
    11     even = odd1 + odd2
    12     
    13 print(sum)
    本题结束。
     



  • 相关阅读:
    EF系列——DbContext 和DbSet
    EF中的实体关系
    EF中的持久化场景
    Sass
    js里==和===的区别 、sass与less的区别 、style,与class区别(精解版)
    HTML页面加载和解析流程 link与script标签
    DesktopNaotu 百度桌面脑图使用事项
    BootStrap4中使用图标
    Bootstrap4
    CDN文件
  • 原文地址:https://www.cnblogs.com/foundkey/p/6071390.html
Copyright © 2011-2022 走看看