zoukankan      html  css  js  c++  java
  • 欧拉计划002

      

    斐波那契数列中的每一项被定义为前两项之和。从1和2开始,斐波那契数列的前十项为:

    1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

    考虑斐波那契数列中数值不超过4百万的项,找出这些项中值为偶数的项之和。

    ——————————————————————————————————————————

    提起斐波拉契数列,自然联想到课本上递归函数的经典应用,于是有了如下熟悉的一串:

    #include <stdio.h>
    #include <stdlib.h>
    
    int fb(int n)
    {
    
        if(n==1||n==2)
            return n;
        else
        {
            n=fb(n-1)+fb(n-2);
            return n;
        }
    
    }
    
    int main(void)
    {
        int n,sum=0;
    
    
        for(n=1;fb(n)<=4000000;n++)
            if(!(fb(n)%2)) sum+=fb(n);
            
        printf("偶数项之和:%d",sum); 
        return 0;
    }

    输出结果:4613732;

    值得一提的是,看到的一位网友(来自“http://blog.csdn.net/k7060784/article/details/7513122”)的处理方法:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
        int i,j,n;
    
        for(i=1,j=1,n=0;i<4000000&&j<4000000;)
        {
            i+=j;
            if(i%2==0) n+=i;
            j+=i;
            if(j%2==0) n+=j;
        }
        printf("%d\n",n);
    return 0;
    
    }

    输出结果一致(由此证实我的程序是对的^_^ ),这样的结构也很清晰啊!

  • 相关阅读:
    #include <boost/scoped_ptr.hpp>
    #include <boost/function.hpp>
    #include <boost/bind.hpp>
    8.4散列表查找
    #include <boost/array.hpp>
    异常
    lambda
    #include <amp.h>
    #include <bitset>
    #include <hash_set>
  • 原文地址:https://www.cnblogs.com/hhccdf/p/2962308.html
Copyright © 2011-2022 走看看