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)
    本题结束。
     



  • 相关阅读:
    SAP 用户权限解剖
    效率极低人群的七大习惯你占了几项? 迎客
    数据库到底用不用外键 迎客
    办公室生存——与人相处的30个原则 迎客
    虚拟机 VirtualBox 迎客
    fancybox 迎客
    遥志代理服务器软件CCProxy 迎客
    JRE和JDK的区别 迎客
    小众软件 迎客
    网络推广方法汇集 迎客
  • 原文地址:https://www.cnblogs.com/foundkey/p/6071390.html
Copyright © 2011-2022 走看看