The Collatz series is a mathematical sequence that starts with a positive integer
(let say n).
Now, the next numbers of the sequence is calculated as:
# If the previous term is even then the next term will be half of the previous term.
(if the previous term is ‘n’ the next term will be ‘n/2’)
# If the previous term is odd then the next term will be 3 times of the previous term plus 1.
(if the previous term is ‘n’ the next term will be ‘3n + 1’)
This will be continued till the term becomes 1.
For example, if the starting term be 6 then the sequence will be:
INPUT: Any positive integer ‘n’
OUTPUT: The Collatz Series
PROCESS:
Step 1: [Taking the input]
Read n [Starting integer]
Step 2: [Finding the Collatz Series]
While n≠ 1 repeat
Print n
[If n is odd]
if n mod 2≠0 then
Set n <- 3×n + 1
[If ‘n’ is even]
else
Set n <- n/2
[End of ‘if-else’]
[End of ‘while’ loop]
Step 3: Stop.
SPACE COMPLEXITY:
The space complexity of this program is O(1) as it requires a constant number of memory spaces for any given input.
Related