joj1277

 1277: Fibonacci Freeze


Result TIME Limit MEMORY Limit Run Times AC Times JUDGE
3s 8192K 2367 561 Standard

The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are defined by the recurrence:

 

Write a program to calculate the Fibonacci Numbers.

Input and Output

The input to your program would be a sequence of numbers smaller or equal than 500, each on a separate line, specifying which Fibonacci number to calculate.

 

Your program should output the Fibonacci number for each input value, one per line.

Sample Input

 

5

7

11

Sample Output

 

The Fibonacci number for 5 is 5

The Fibonacci number for 7 is 13

The Fibonacci number for 11 is 89

 

 


This problem is used for contest: 111 


Submit / Problem List / Status / Discuss

 
 
由于要求500项斐波那契数列,用到大数加法。直接在递推写斐波那契数列的程序中将其中的加法替换。
 1 #include <stdio.h>
2 #include <string.h>
3
4 void add(char *a, char *b, char *c)
5 {
6 int i, j, i1, i2, tmp, carry;
7
8 int len1 = strlen(a);
9 int len2 = strlen(b);
10 char ch;
11
12 i1 = len1-1;
13 i2 = len2-1;
14 j = carry = 0;
15
16 for ( ; i1>=0 && i2>=0; --i1, --i2, ++j)
17 {
18 tmp = a[i1]-'0'+b[i2]-'0'+carry;
19 carry = tmp / 10;
20 c[j] = tmp % 10 + '0';
21 }
22
23 while (i1 >= 0)
24 {
25 tmp = a[i1--] - '0' + carry;
26 carry = tmp / 10;
27 c[j++] = tmp % 10 + '0';
28 }
29 while (i2 >= 0)
30 {
31 tmp = b[i2--] - '0' + carry;
32 carry = tmp / 10;
33 c[j++] = tmp % 10 + '0';
34 }
35
36 if (carry != 0)
37 {
38 c[j++] = carry + '0';
39 }
40 c[j] = '\0';
41 for (i=0, --j; i<j; ++i, --j)
42 {
43 ch = c[i];
44 c[i] = c[j];
45 c[j] = ch;
46 }
47 a[i1] = '\0';
48 b[i2] = '\0';
49 }
50
51
52 int main(void)
53 {
54 int val;
55
56 char a[1000], b[1000], c[1000];
57
58
59 while (scanf("%d", &val) == 1)
60 {
61 a[0] = '0';
62 a[1] = '\0';
63 b[0] = '1';
64 b[1] = '\0';
65
66 if (0 == val)
67 {
68 c[0] = '0';
69 c[1] = '\0';
70 }
71 else if (1 == val)
72 {
73 c[0] = '1';
74 c[1] = '\0';
75 }
76 else
77 {
78 for (int i=2; i<=val; i++)
79 {
80 add(a, b, c);
81 strcpy(a, b);
82 strcpy(b, c);
83 }
84 }
85
86 printf("The Fibonacci number for %d is %s\n", val, c);
87 }
88
89 return 0;
90 }

你可能感兴趣的:(OJ)