Given an integer N. The task is to find the number in the range from 1 to N-1 which is having the maximum number of terms in its Collatz Sequence and the number of terms in the sequence.
The collatz sequence of a number N is defined as:
- If N is Odd then change N to 3*N + 1.
- If N is Even then change N to N / 2.
For example let us have a look at the sequence when N = 13:
13 -> 40 -> 20 -> 10 -> 5 > 16 -> 8 -> 4 -> 2 -> 1
Output: (9, 20)
9 has 20 terms in its Collatz sequence
Output: (27, 112)
27 has 112 terms
As in the above example discussed for N = 13, collatz sequence for N = 13 and N = 40 have similar terms except one, that ensures there may be an involvement of dynamic programming to store the answer for subproblems and reuse it.
But here normal memoization will not work because at one step we are either making a number large from itself ( in above example N = 13 is depending upon the solution of N = 40 ) or dividing by 2 ( N = 40 solution depends upon the solution of N = 20 ).
So instead of using a dp array we will use a Map/ dictionary data structure to store the solution of subproblems and will perform the normal operation as discussed in the collatz sequence.
Below is the implementation of the above approach:
- Program to implement Collatz Conjecture
- G-Fact 21 | Collatz Sequence
- Program to print Collatz Sequence
- Find maximum length Snake sequence
- Minimum sum possible of any bracket sequence of length N
- Find minimum length sub-array which has given sub-sequence in it
- Total number of odd length palindrome sub-sequence around each centre
- Maximum sum Bi-tonic Sub-sequence
- Longest sub-sequence with maximum GCD
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array
- Maximum sub-sequence sum such that indices of any two adjacent elements differs at least by 3
- Maximum contiguous decreasing sequence obtained by removing any one element
- Maximum Sum Subsequence of length k
- Maximum sum subarray of even length
- Maximum length of segments of 0's and 1's
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.