(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

转载于:https://www.cnblogs.com/cpoint/p/3367342.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值