Project Euler 14 solution

By Lu.Qian.

Question:

Longest Collatz sequence

Problem 14

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.

 
My solution:

Using cursive function fo find a specific numbers Collatz sequence number, then store it into a 'map' container.

Implementation by C++:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cmath>
 4 #include <map>
 5 using namespace std;
 6 
 7 int find_fac(int toBeFind, map<long long int , int> &fac){
 8     int cnt = 0;
 9     long long int rec = toBeFind;
10     while(rec != 1 && fac.find (rec) == fac.end()){
11         cnt++;
12         if(rec % 2 == 0)
13             rec /= 2;
14         else
15             rec = rec * 3 + 1;
16     }
17     return fac[toBeFind] = cnt + fac[rec];
18 }
19 
20 int main()
21 {
22     map<long long int,int> fac;
23     fac[1] = 1;
24     long int max = 0;
25     long long int rec[2] = {0,0};
26     long long int cnt = 2;
27     while(cnt < 1000000){
28         rec[0] = fac[cnt] = find_fac(cnt,fac);
29         if(rec[0] > max){
30             max = rec[0];
31             rec[1] = cnt;
32             cout<<cnt<<endl;
33         }
34         cnt++;
35     }
36     cout<<max<<endl;
37     cout<<rec[1]<<endl;
38     return 0;    
39 }

The code I wrote and post here crashed due to its recursive function. So this version I use simple iterative function to find out the sequence item number. And it works well. Running time would be within 10 mins.

 

转载于:https://www.cnblogs.com/QianL/p/5677481.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值