• 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

  • 相关阅读:
    冲刺NO.2
    冲刺NO.1
    用户场景描述
    【洛谷T2695 桶哥的问题——吃桶】
    【洛谷P4445 【AHOI2018初中组】报名签到】
    清北学堂2019.5.4
    清北学堂2019.5.3
    清北学堂2019.5.2
    清北学堂培训2019.5.1
    清北学堂培训2019.4.30
  • 原文地址:https://www.cnblogs.com/lake19901126/p/3047178.html
Copyright © 2020-2023  润新知