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.