zoukankan      html  css  js  c++  java
  • projecteuler第二题

    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.

    这个问题是求小于4百万的fibonacci序列中的偶数的和

    第一个思路:构造数列,累加其中的偶数

    vector<int> data;
    data.push_back(1);
    data.push_back(2);
    int cur_index = 2;

    int sum = 2;
    while(true)
    {
    int cur_num = data[cur_index-1]+data[cur_index-2];
    if(cur_num>4000000)
    {
    break;
    }
    data.push_back(cur_num);
    if(cur_num%2==0)
    {
    sum+= cur_num;
    }
    cur_index++;


    }

    cout<<sum<<endl;

    第二个思路:

    因为序列数据是两奇一偶,所以可以跳跃式累加

    int sum = 2;
    int cur_num = 2;
    int prev_num = 1;

    int next_num,next_next_num;

    while(true)
    {
    next_num = prev_num + cur_num;
    next_next_num = next_num + cur_num;
    cur_num = next_num+next_next_num;
    if(cur_num > 4000000)
    {
    break;
    }
    sum += cur_num;
    prev_num = next_next_num;

    }

    cout<<sum<<endl;

  • 相关阅读:
    java——spring中bean的作用域
    java——线程池
    java—如何解决缓存穿透
    java—锁的学习研究
    java--springmvc
    java—多线程—notify/notifyAll
    php 基础复习 2018-06-18
    php 基础复习 2018-06-19
    php 以单下划线或双下划线开头的命名
    mysql 常用sql语句
  • 原文地址:https://www.cnblogs.com/guochen/p/6849270.html
Copyright © 2011-2022 走看看