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;

  • 相关阅读:
    L1-021 重要的话说三遍
    L1-020 帅到没朋友
    pytest--钩子
    pytest--allure
    pytest--常用插件
    pytest--高级用法
    pytest--配置文件
    pytest--控制运行
    pytest--fixture
    pytest--使用前提
  • 原文地址:https://www.cnblogs.com/guochen/p/6849270.html
Copyright © 2011-2022 走看看