zoukankan      html  css  js  c++  java
  • ProjectEuler 2

    斐波那契数列中不超过400万的偶数之和

    /**
    * 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.
    */

    代码:

    private static int sumEvenFib(int N) {
    if (N < 2)
    return 0;
    if (N < 8)
    return 8;
    int sum = 10, ppre = 2, pre = 8;
    int tmp = ppre + 4 * pre;
    while (tmp < N) {
    sum += tmp;
    ppre = pre;
    pre = tmp;
    tmp = ppre + 4 * pre;
    }
    return sum;
    }

    public static void main(String[] args) {
    print(sumEvenFib(4000000));
    }

    思想:

    最基本的做法就是一项项迭代,然后判断该项是否偶数然后相加,这样需做n次计算

    斐波那契数列中的偶数只可能是A3n+2 项,我们只要找数列中的偶数和,那么找到数列中偶数之间的关系,则只需计算n/3,可以减少2倍的时间

    经求有A3n+2=4*A3n-1+A3n-4

  • 相关阅读:
    1112评论
    1029 C语言文法
    0909编译原理理解和解释
    复利计算4.0-单元测试
    命令解析程序的编写
    《构建之法》1、2、3章思考与感想
    复利计算4.0
    实验三的分析与总结
    复利计算(更新)
    单、复利计算程序
  • 原文地址:https://www.cnblogs.com/lake19901126/p/3047178.html
Copyright © 2011-2022 走看看