Extra Credit 3

Due: November 14, 2025
Points: 30


In the given examples, what you type is in red and the program prints what is in black. The symbol means a carriage return (return, enter).

Your program output should look like the output in the examples, except that what you type won’t be in red.

Define the function:

n.2 for even n, 3n+1 for odd n

The Collatz conjecture says that, if you iterate this sequence for any initial value of n, then eventually the sequence will reach the number 1.

For a number n, let k be the least number of iterations needed to reach the number 1 (excluding the initial value). Then k is called the total stopping time of n. For example, if n = 29, then the sequence is:


29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
and so the total stopping time of 29 is 18.

Write a program that takes as input a positive integer and prints both the sequence and the total stopping time for that integer. For example:


Where should I start? 29
29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
The total stopping time for 29 is 18

In this next example, all numbers on the second to fourth lines are really just one long line.


Where should I start? 12345
12345 37036 18518 9259 27778 13889 41668 20834 10417 31252 15626 7813 23440 11720 5860 2930 1465 4396 2198 1099 3298 1649 4948 2474 1237 3712 1856 928 464 232 116 58 29 88 44 22 11 3417 52 26 13 40 20 10 5 16 8 4 2 1
The total stopping time for 12345 is 50

Call your program “collatz.py”.


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
MHI 289I, Programming in Health Informatics
Version of November 3, 2025 at 4:08PM

You can also obtain a PDF version of this.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh