这样的水题也被我WA了几次,惭愧啊! 就是就是没有注意当i > j 时输出位置不变的问题
看来做题目一定要细心,小心陷阱
我的代码:
1#include <stdio.h>
2#include <stdlib.h>
3
4int cylen (int a, int b)
5{
6 int max = 0;
7 for (int i = a; i <= b; i ++)
8 {
9 int n = i;
10 int count = 1;
11 while ( n != 1)
12 {
13 count ++;
14 if ( n % 2 == 0)
15 n = n / 2;
16 else
17 n = 3 * n + 1;
18 }
19
20 if (max < count)
21 max = count;
22 }
23 return max;
24}
25
26int main ()
27{
28 int i, j;
29 while ( scanf ("%d %d", &i, &j) != EOF )
30 {
31 int index;
32 if (i > j)
33 {
34 index = i;
35 i = j;
36 j = index;
37 printf ("%d %d %d\n", j, i, cylen (i, j));
38 }
39 else
40 printf ("%d %d %d\n", i, j, cylen (i, j));
41 }
42
43 //system ("pause");
44 return 0;
45}
46
网上的代码:用递归做的,两个代码复杂度完全一样
1# include <stdio.h>
2#include <stdlib.h>
3int fun(long a ,int len)
4{
5 if (a ==1)
6 return len;
7 else if (a %2 ==0)
8 return fun(a/2,len+1);
9 else return fun(3*a+1,len +1);
10}
11int main()
12{
13 unsigned long a,b;
14 unsigned long i,max,temp;
15
16 while (scanf("%ld%ld",&a,&b)!=EOF)
17 {
18 printf("%ld %ld ",a,b);
19 if(a>b) {i = a;a=b;b=i;}
20 for (max = 0,i = a; i <= b; i ++)
21 {
22 temp = fun(i,1);
23 if (max < temp)
24 max = temp;
25 }
26 printf("%ld\n",max);
27 }
28 //system ("pause");
29 return 0;
30}
31
posted on 2010-08-23 19:42
雪黛依梦 阅读(338)
评论(0) 编辑 收藏 引用 所属分类:
简单题