problem 14

 1 #include"pub.h"
 2 #include <map>
 3 
 4 long cnt=0;
 5 map<long,long> mp;
 6 long collatz(long n)
 7 {
 8     if(mp.find(n)!=mp.end())
 9         return mp[n];
10     else
11     {
12         if(n<=1)
13         {
14             return 1;
15         }
16         else
17         {
18             if(n&1)
19                 return collatz(3*n+1)+1;
20             else
21                 return collatz(n/2)+1;
22         }
23     }
24 }
25 
26 int p14()
27 {
28     long max=0;
29     long result=0;
30     for(long i=1; i<1000000L; i++)
31     {
32         cnt=collatz(i);
33         mp[i]=cnt;
34         if(cnt>=max)
35         {
36             max=cnt;
37             result=i;
38         }
39     }
40     cout<<result<<","<<max<<endl;
41     return 0;
42 }

 

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.

http://projecteuler.net/problem=14

 

结果算出来一直不正确。

 

 

今天突然想到有可能是数据溢出导致的。于是将定义的数字long型改为long long。结果正确!   -2012-12-14

 

posted @ 2012-11-19 16:19  黄牛  阅读(198)  评论(0编辑  收藏  举报