首页 > 其他 > 详细

Project Euler 14 solution

时间:2016-07-17 12:12:41      阅读:216      评论:0      收藏:0      [点我收藏+]

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 here:

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

 

But it runs collapsed with no error no exception.... I will change a PC to run it.

 

Project Euler 14 solution

原文:http://www.cnblogs.com/QianL/p/5677481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!