TCS OA-32 2024
Problem Description
You are tasked with implementing solutions related to the Collatz sequence for a given positive integer n. The Collatz sequence for a number n is defined by the following rules:
- If n is even, the next term is n/2.
- If n is odd, the next term is 3n+1.
- The sequence continues until n reaches 1.
Constraints
1≤ n ≤20
Task 1: Generate the Collatz Sequence
Can you implement a function to generate the Collatz sequence for a given integer nnn?
- Input: A positive integer n.
- Output: Print the Collatz sequence starting from n until it reaches 1.
Sample Input:
5
Sample Output:
5,16,8,4,2,1
Explanation:
Starting with the number 5:
- 5 is odd: Apply the rule 3n+1 → 3×5+1=16
- 16 is even: Apply the rule n/2 → 16/2=8
- 8 is even: Apply the rule n/2 → 8/2=4
- 4 is even: Apply the rule n/2 → 4/2=2
- 2 is even: Apply the rule n/2 → 2/2=1
- 1 is the end of the sequence.
Thus, the entire sequence starting from 5 is: 5, 16, 8, 4, 2, 1.
Task 2: Find the Maximum Length of Collatz Sequence
Can you implement a function to determine the k value that produces the longest Collatz sequence among all integers from 1 to n?
- Input: A positive integer n.
- Output: Identify the integer k (where 1≤k≤n) that produces the longest Collatz sequence, along with the length of that sequence.
Sample Input:
10
Sample Output:
9,20
Explanation:
We calculate the Collatz sequence for each integer k from 1 to 10.
After calculating, we find that k=9 produces the longest sequence with a length of 20.
Task 3: Find the Maximum Value in the Collatz Sequence
Can you implement a function to determine the k value that produces the maximum value in its Collatz sequence among all integers from 1 to n?
- Input: A positive integer n.
- Output: Identify the integer k (where 1≤k≤n) that produces the maximum value in its Collatz sequence, along with that maximum value.
Sample Input:
10
Sample Output:
9,52
Explanation:
We calculate the maximum value for each integer k from 1 to 10.
From all values, we find that k=9 produces the maximum value in its Collatz sequence, which is 52.