How to Solve the 3n+1 Problem in Python?

Estimated read time 2 min read

The 3n+1 Problem, also known as the Collatz Conjecture, is a mathematical problem that asks you to determine the number of steps it takes to reach 1 by repeatedly applying the following rules to a positive integer n:

  • If n is even, divide it by 2.
  • If n is odd, multiply it by 3 and add 1.

Here is an example of how to solve this problem in Python:

def collatz(n):
    steps = 0
    while n != 1:
        if n % 2 == 0:
            n //= 2
            n = 3*n + 1
        steps += 1
    return steps

# test the function with a sample input
n = 27

In this solution, we define a function collatz that takes a positive integer n as input. The function initializes a variable steps to 0 to count the number of steps.

The function then repeatedly applies the rules of the 3n+1 problem until n reaches 1. If n is even, the function divides it by 2 using integer division (//). If n is odd, the function multiplies it by 3 and adds 1. The function increments the steps counter after each step.

After reaching 1, the function returns the number of steps taken to reach 1.

In the main part of the script, we test the function with a sample input integer n and print out the result.

To use this code with other inputs, simply replace n with the desired input integer.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply