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;

  • 相关阅读:
    golang通知协程退出
    Linux Centos7下安装Elasticsearch
    es
    Laravel 别名 Facades的用法
    SVN使用时遇到的小问题
    http 重定向到 https
    Git-版本回退
    selenium---上传文件(非input标签)
    selenium---生成BeautifulReport报告
    windows搭建ngnix图片服务器
  • 原文地址:https://www.cnblogs.com/guochen/p/6849270.html
Copyright © 2011-2022 走看看