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