This is project euler problem 14. Really interesting and mathematically challenging one.
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
Source: Project Euler.
The below figure will explain the problem precisely.
I tried the tail recursive way first..!! But its too slow and it took hours to run.. In debug mode, stack is used even for tail recursion.. so, it went useless to do 1 million function calls every time. so, moved into a iterative way.
Just a brute force algorithm for 1 million values took around 10-15 minutes to run. But, the 1-minute rule given by project euler is not followed in this program.. :)
There are better ways to do.. But since there seems no valid applications for this series, am just leaving it here..
- gMax is the maximum count of the numbers in the series
- gI is the number which yields this max count