evan

For the lasting love

导航

3N+1数链

Description:

给出一个数n

1. if n=1,then end

2. if n is an odd number, then n = 3*n+1, else n=n/2

3. goto step 1

example n = 22

22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

the length of the above serial is 16, so is the length of 22

Question is that two integer a,b (a<=b) is given, work out the max length of all integer i (a<=i<=b), and print it

 

Solution:

1 #include <stdio.h>
2
3  int LinkLen(int x)
4 {
5 int len=1;
6 while (x!=1)
7 {
8 if (x%2)x=3*x+1;
9 else x/=2;
10
11 len++;
12 }
13
14 return len;
15 }
16
17  int main ()
18 {
19 int maxLen=0;
20 int a=0,b=0,i=0,len=0;
21
22 while (scanf ("%d%d",&a,&b)!=EOF)
23 {
24 for (i=a; i<=b; i++)
25 {
26 len = LinkLen(i);
27 if (len>maxLen)
28 maxLen = len;
29 }
30
31 printf ("%d\n",maxLen);
32 maxLen = 0;
33 }
34
35 return 0;
36 }

 

posted on 2010-06-22 12:42  evander  阅读(141)  评论(0)    收藏  举报