Problem 2

 

 

题目

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.

提醒:even-valued 是偶数的意思,英文不好的同学表示:-_-|||

最简单的解答

public static long q2(int max) {
            long s1 = 1;
            long s2 = 2;

            long sum = 2;
            while (s2 <= max) {
                s1 = s1 + s2;//(s3)
                s2 = s1 + s2;//(s4 = s3 + s2)
                if (s1 <= max && s1 % 2 == 0) {
                    sum += s1;
                }
                if (s2 <= max && s2 % 2 == 0) {
                    sum += s2;
                }
            }
            return sum;
        }

        public static void test() {
            var t1 = DateTime.Now;
            Console.WriteLine(" " + q2(4000000) + " cast time " + (DateTime.Now - t1).TotalSeconds);

        }

 

 

运行结果

image

 

当然还有很多可以简化复杂的方法。

第一点:比如对%2,如果c#运行的时候,没有对其特别优化(判断最后一位是否是0),则可以考虑使用规律来减少判断。规律是:

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

S1奇数,S2偶数,S3奇=奇+偶,S4奇数=奇数+偶数,S5=偶数。。。

也就是说,从2开始,每隔2个就是一个偶数。

甚至可以得出一个偶数的递推公式。

O1=S2=2;

O2=S5=S3+S4;

O3=S8=S6+S7;

.......

O2=O1+1   +   O1=O1*2+1=。。。

O3=O2+S4+O2

....

好吧。。最终可以得出一个通项公式;

参考这里 http://www.cnblogs.com/zhouyinhui/archive/2011/01/06/1929153.html

挖个坑。有时间再填满中间漏掉的推理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值