Collatz Sequence
Problem
Start with a positive integer n. If n is even, the next number is n / 2. If n is odd, the next number is 3n + 1. Repeat until you reach 1. Read n and print all numbers of the sequence, including n and 1, on one line separated by a space.
Constraints
- 1 <= n <= 10^6
Examples
Input
6
Output
6 3 10 5 16 8 4 2 1
Solutions
We follow the two rules until we reach 1. Nobody has proved that every start number reaches 1 (the Collatz conjecture), but it is true for all numbers tested so far.
/*
* Problem : Print the Collatz sequence of a number.
* Input : One positive integer n.
* Output : The sequence from n to 1 on one line, separated by a space.
* Approach: If the number is even, halve it. If it is odd, multiply by 3 and add 1.
* Time : Unknown (depends on n)
* Space : O(length)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = new Scanner(System.in).nextLong();
StringBuilder line = new StringBuilder();
// Step 1: Write the first number of the sequence.
line.append(number);
// Step 2: Repeat until the number is 1.
while (number != 1) {
// Step 3: If the number is even, divide it by 2. Otherwise multiply it by 3 and add 1.
if (number % 2 == 0) {
number = number / 2;
} else {
number = 3 * number + 1;
}
// Step 4: Write the new number after a space.
line.append(" ").append(number);
}
// Step 5: Print the sequence. We use long, because the numbers can grow large before they fall to 1.
System.out.println(line);
}
}
Hints (2)
- What is the rule for even numbers? And for odd numbers?
- When do you stop?