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



  • 相关阅读:
    HDOJ 1877
    POJ 2210
    HDOJ 1230(火星A+B)
    大数想减
    HDU 2115
    HDOJ 1234
    HDOJ 3784
    HDOJ3782(xxx定理)
    C# 使用 Stopwatch 测量代码运行时间
    SQL返回当前天是星期几
  • 原文地址:https://www.cnblogs.com/foundkey/p/6071390.html
Copyright © 2011-2022 走看看