Home CPSC 110

Lab 7: Collatz Conjecture

 

Objective

To gain experience with nesting control structures.


 

Task

The Collatz Conjecture states that if we take any integer $N$, and repeatedly do the following steps to it:

  1. If it's even, divide it by two
  2. If it's odd, multiply it by 3 and add 1.
Then we will eventually hit 1.

For example if we start with 5, we go though the following steps:

  1. 5 (starting number)
  2. 16 (times by 3 and add 1)
  3. 8 (divide by 2)
  4. 4 (divide by 2)
  5. 2 (divide by 2)
  6. 1 (divide by 2)

This conjecture was raised by mathematician Lothar Collatz in 1937. Every number anyone has ever tried has eventually gotten to 1, but mathematicians have not been able to prove if this will work for all numbers or not.

You should write a program which reads in the starting number and prints out the numbers in the sequence until you hit 1.


 

Details

  1. Start by asking the user to enter the initial number.
  2. Create a loop which will keep looping until the number hits 1.
  3. Inside the loop, check if the number is even or odd (using the % operator)
  4. If it was even, divide the number by two (saving the result back into the number).
  5. If it was odd, multiply the number by 3 and add 1 (again saving the result).
  6. After the loop print out that 1 was reached.

 

Example Run

Below is an example run of how this program should work:

Enter a number: 3
3
10
5
16
8
4
2
Got to 1

 

Extra Credit

For extra credit, make your program also print out the number of steps the process took. That would look like this:

Enter a number: 3
3
10
5
16
8
4
2
Got to 1 in 7 steps

 

Submitting

When you are finished, please submit the .py file for the lab on Canvas. To do so, you'll need to navigate to where you saved the file on your computer.

Copyright © 2024 Ian Finlayson | Licensed under a Creative Commons BY-NC-SA 4.0 License.