签名题,注意别超范围,递归求解。。。
题目链接:http://202.197.224.59/OnlineJudge2/index.php/Problem/read/id/1142
Collatz Conjecture | ||
Accepted : 117 | Submit : 716 | |
Time Limit : 8000 MS | Memory Limit : 1048576 KB |
考拉兹猜想,又称为3n+1猜想、冰雹猜想、角谷猜想、哈塞猜想、乌拉姆猜想或叙拉古猜想,是指对于每一个正整数,如果它是奇数,则对它乘3再加1,如果它是偶数,则对它除以2,如此循环,最终都能够得到1。 如n = 6,根据上述数式,得出 6→3→10→5→16→8→4→2→1 。步骤中最高的数是16,共有8个步骤。现在给定任意整数a和b,问对所有a ≤ n ≤ b,一共经过多少步后才能都得到1,其中最高的数是多少。 Input有多组测试数据。每组测试数据占一行,包含两个正整数1 ≤ a ≤ 1000000和a ≤ b ≤ a + 10。输入以EOF结束。 Output对每组测试数据,输出步数和最高数,用空格隔开。 Sample Input6 6 11 12 23 33 Sample Output8 16 23 52 360 9232 SourceXTU OnlineJudge |
CODE:
2int main()
3 {
4 int a,b,i;
5 __int64 count,max,t;
6 while (scanf("%d%d",&a,&b)!=EOF)
7 {
8 count=0;max=a;
9 for (i=a;i<=b;i++)
10 {
11 t=i;
12 while (t!=1)
13 {
14 if (t%2)
15 {
16 t=t*3+1;
17 }
18 else
19 {
20 t=t/2;
21 }
22 if(t>max)
23 max=t;
24 count++;
25 }
26 }
27 printf("%I64d %I64d\n",count,max);
28 }
29 return 0;
30 }
CODE:
2 #include <string.h>
3 #define MAX_LEN 100001
4 #include <stdio.h>
5
6 __int64 count ;
7 __int64 Max_N[MAX_LEN + 10] = {0};
8 __int64 sum1 = 0;
9
10
11 void GetMaxL(int n)
12 {
13 count++;
14 Max_N[sum1++] = n;
15 if(n == 1) return ;
16 if(n & 1) GetMaxL(n * 3 + 1);
17 else GetMaxL( n/2 );
18 }
19
20
21 int cmp(const void *a , const void *b)
22 {
23 return *(int*)b - *(int*)a;
24 }
25
26
27 int main()
28 {
29 int beg , end;
30 while(~scanf("%d%d", &beg , &end))
31 {
32 int i;
33 count = -1;
34 sum1 = 0;
35 for(int i = beg ; i <= end ; i++)
36 {
37 GetMaxL(i);
38 }
39 __int64 m = end - beg; //由于是所有的数一共经过多少步变为1
40 qsort(Max_N,sum1,sizeof(__int64),cmp);//排序
41 printf("%I64d " , count - m);
42 printf("%I64d\n", Max_N[0]); //最大数
43 }
44 return 0;
45 }