joj1277

 1277: Fibonacci Freeze


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s8192K2367561Standard

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 }

转载于:https://www.cnblogs.com/RootJie/archive/2012/01/27/2330171.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值