THINK FIRST·CODE LATER

← All labs

The Collatz sequence

Problem

Start with a positive integer n. If n is even, divide it by 2; if odd, replace it by 3n + 1. Repeat until n = 1 (mathematicians believe this always happens, but nobody has proved it).

Write Collatz: read n (use long) and print the first 15 steps of the sequence (then ... if there are more), the number of steps and the highest value reached:

Sequence: 6 3 10 5 16 8 4 2 1
Steps: 8
Highest value: 16

For n < 1 print Enter a positive number.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l7-4-data-1.txt

6
What your program must print for l7-4-data-1.txt
Sequence: 6 3 10 5 16 8 4 2 1
Steps: 8
Highest value: 16

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l7-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content l7-4-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.