欧拉计划之题目2:在斐波那契数列中,找出4百万以下的项中值为偶数的项之和。

---恢复内容开始---

本题来自:http://pe.spiritzhang.com/index.php/2011-05-11-09-44-54/3-24

分析:400万项之和,数太大,故使用usinged long long。

          int  字节:4  取值范围:-2147438648~+2147438647
       long int  字节:4  取值范围:-2147438648~+2141438647
long long int  字节:8      取值范围:-9223372036854775808~+9223372036854775807

 1 #include <stdio.h>
 2 #define TRUE 1
 3 
 4 void main()
 5 {
 6     unsigned long long sum=0;            //偶数和
 7     unsigned int x=0,y=1,z,conut,conut_num;//x,y,z分别表示第一、第二、第三个数。conut表示项数,conut_num表示求和中加的次数
 8     while(TRUE)
 9     {
10         z=x+y;                 //第三个数是前两个数的和
11 if(z%2==0)              //判断这数是不是偶数
12 { 13 sum+=z; 14 conut_num++; 15 } 16 conut++; 17 x=y;y=z;      18 if(conut>=4000000) 19 break; 20 } 21 printf("共有%d个数被相加,和为%lld\n",conut_num,sum); 22 }

扩展知识:long long int不是所有编译器都支持的,有些支持这种数据类型的,可能是真支持,也可能是模拟支持,总之它不是标准类型。在.NET4框架中,有64位的长整型数据,这个框架下的所有语言都能使用,但不是所有语言本身都有定义这样的数据类型,也就是说,你尽可使用_int64或System.Int64来定义64位的整数,但未必有long long这样的定义。

VS2010的.NET4中,C#语言的int是32位的,long是64位的,但其C++的int和long都是32位的,后者支持64位的long long类型。

如果在linux系统中,gcc编译,long long是C99才有的,所以gcc编译时候:

gcc -std=c99 "文件名"
 

分析:

        思路1:逐项判断并累加。

        思路2:找出相邻偶数之间的关系,如下:

序号:1  2  3  4  5  6  7  8  9  10  11

值:        2           8          34           144

由:a8 = a6 + a7

      = a4 + a5 + a5 + a6

      = a2 + a3 + 2a5 + a5 +a4

      = a2 + 4a5

可得:

a(n+6) = a(n) + 4a(n+3)

验证:n = 5

a11 = a5 + 4*a8 = 8 + 4*34 = 144

所以:

a(n+6) = a(n) + 4a(n+3)

解:

 1 #include <stdio.h>
 2 #define MAX_NUM        4000000
 3 
 4 //依次返回斐波那契数
 5 int Fibo()
 6 {
 7     static int n1 = 0;
 8     static int n2 = 1;
 9     int t;
10 
11     t = n1 + n2;
12     n1 = n2;
13     n2 = t;
14 
15     return t;
16 }
17 
18 //依次返回斐波那契数(只返回偶数)
19 int FiboEven()
20 {
21     static int n1 = 2;
22     static int n2 = 8;
23     int t;
24 
25     t = n1 + 4 * n2;
26     n1 = n2;
27     n2 = t;
28 
29     return t;
30 }
31 
32 int main()
33 {
34     /*
35     int sum;
36     int n;
37 
38     sum = 0;
39     while ((n=Fibo()) < MAX_NUM)
40     {
41         if(0 == n%2)
42             sum += n;
43     }
44     printf("%d\n", sum);
45     */
46 
47     int sum;
48     int n;
49 
50     sum = 10;
51     n = 0;
52     while ((n=FiboEven()) < MAX_NUM)
53         sum += n;
54     printf("%d\n", sum);
55 
56     return 0;
57 }
View Code
原文地址:https://www.cnblogs.com/orange1438/p/2913556.html