Ray's playground

 

Project Euler Problem 25

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class BigNumber
 5 {
 6 private:
 7     int num[1000];
 8 
 9 public:
10     BigNumber(int number)
11     {
12         for(int i=999; i>=0; i--)
13         {
14             num[i] = number % 10;
15             number /= 10;
16         }
17     }
18 
19     bool Contains1000Digits()
20     {
21         return num[0> 0;
22     }
23 
24     BigNumber operator+(const BigNumber& bigNumber)
25     {
26         BigNumber sum(0);
27         int temp;
28         int over = 0;
29         for(int i=999; i>=0; i--)
30         {
31             temp = num[i]+bigNumber.num[i]+over;
32             sum.num[i] = temp % 10;
33             over = temp / 10;
34         }
35         return sum;
36     }
37 
38     void print()
39     {
40         for(int i=0; i<1000; i++)
41         {
42             cout << num[i];
43         }
44         cout << endl;
45     }
46 };
47 
48 int main()
49 {
50     BigNumber F1(1);
51     BigNumber F2(1);
52     int i=2;
53     while(true)
54     {
55         i++;
56         F1 = F1+F2;
57         if(F1.Contains1000Digits())
58         {
59             break;
60         }
61         i++;
62         F2=F1+F2;
63         if(F2.Contains1000Digits())
64         {
65             break;
66         }
67     }
68     cout << i << endl;
69     cin.get();
70     return 0;
71 }

posted on 2011-03-21 21:45  Ray Z  阅读(239)  评论(0编辑  收藏  举报

导航