(Problem 14)Longest Collatz sequence

The following iterative sequence is defined for the set of positive integers:

n  n/2 (n is even)
n  3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:

13   40   20   10   5   16   8   4   2   1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

方法1:
 1 #include<stdio.h>

 2 #include<math.h>

 3 #include<string.h>

 4 #include<ctype.h>

 5 #include<stdlib.h>

 6 #include<stdbool.h>

 7 

 8 int powcount(long long n)  //计算2的幂数

 9 {

10     int count=0;

11     while(n>>=1) count++;

12     return count;

13 }

14 

15 bool ispower(long long v)  //判断n是否为2的幂

16 {

17     if(((v & (v - 1)) == 0))  return true;

18     else return false;

19 }

20 

21 int length(long long n)

22 {

23     int sum=1;

24     while(1)

25     {

26         if(n==1) break;

27         if((n & 1)==0)

28         {

29             if(ispower(n)) return sum+powcount(n);

30             else n=n/2;

31         }

32         else n=3*n+1;

33         sum++;

34     }

35     return sum;

36 }

37 

38 int main()

39 {

40     int i,t,k,max=0;

41     for(i=2; i<1000000; i++)

42     {

43         t=length(i);

44         if(t>max)

45         {

46             max=t;

47             k=i;

48         }

49     }

50     printf("%lld\n",k);

51     return 0;

52 }

方法2:

 1 #include<stdio.h>

 2 #include<math.h>

 3 #include<string.h>

 4 #include<ctype.h>

 5 #include<stdlib.h>

 6 #include<stdbool.h>

 7 

 8 int a[1000001];

 9 

10 void find()

11 {

12     long long i,j,k,f,sum,max=0;

13     a[1]=1,a[2]=2;

14     for(j=3; j<1000000; j++)

15     {

16         sum=1,k=i=j;

17         while(1)

18         {

19             if((i & 1)==0)

20             {

21                 i=i/2;

22                 if(i<k)

23                 {

24                     a[k]=sum+a[i];

25                     break;

26                 }

27             }

28             else

29             {

30                 i=3*i+1;

31             }

32             sum++;

33         }

34         if(a[k]>max)

35         {

36             max=a[k];

37             f=k;

38         }

39     }

40     printf("%d\n",f);

41 }

42 

43 int main()

44 {

45     find();

46     return 0;

47 }

 

Answer:
837799

你可能感兴趣的:(sequence)