欧拉项目练习题吧: 题目002

本文介绍了一个计算斐波那契数列中不超过四百万的所有偶数值项之和的C语言程序实现。该程序使用了迭代的方法,并在过程中确保了数值不会超出整数的最大限制。

/*
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.
*/

#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define CEILING 4000000

int sum_fib_even ( const int );

int main( void )
{
  printf ( "Sum of the even-valued terms is %d\n" ,
             sum_fib_even ( CEILING )  ) ;
           
  system("PAUSE"); 
  return 0;
}

int sum_fib_even ( const int ceiling )
{
    int fib_term0 = 0 , fib_term1 = 1 , fib_term2 = 2 ;
    int sum_even  = 0 ;   
   
    while ( fib_term2 <= ceiling) {
          assert ( INT_MAX - sum_even >= fib_term2 ) ;//实在很不放心
          sum_even += fib_term2 ;
         
          fib_term0 = fib_term1 + fib_term2 ;
          fib_term1 = fib_term2 + fib_term0 ;
          fib_term2 = fib_term0 + fib_term1 ;   
    }
   
    return sum_even ;
}

参考博文:

http://www.cnblogs.com/zhouyinhui/archive/2011/01/06/1929153.html

转载于:https://www.cnblogs.com/KBTiller/archive/2011/03/07/1974738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值