Chinaunix首页 | 论坛 | 博客
  • 博客访问: 229363
  • 博文数量: 39
  • 博客积分: 1130
  • 博客等级: 少尉
  • 技术积分: 453
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-26 15:54
文章分类

全部博文(39)

文章存档

2012年(1)

2011年(31)

2010年(7)

分类: C/C++

2011-03-07 16:26:06

/*
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
#include
#include
#include

#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

阅读(3135) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~