Collatz Challenge

Joined
Aug 1, 2023
Messages
1
Reaction score
0
Hello Everyone!
I'm trying to figure out that how this collatz challenge works but i couldn't make it so far and asking for your help:

Python:
number = 27
steps = 0

for i in range(50000):
    if number == 1:
        break
    elif number % 2 == 0:
        number//2 == number
        steps = steps + 1
    elif number %2 != 0:
        number = number*3 + 1
        steps = steps + 1
   
if number == 1:
    print("It took", steps, "steps")
else:
    print("The number didn't reach 1 yet")
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
This ChatGPT generated explanation is satisfactory for you?

Collatz conjecture, also known as the 3n+1 problem or Collatz problem.
The Collatz conjecture is an unsolved mathematical problem that concerns the following process:

Given a positive integer n, the Collatz conjecture states that you can transform n into 1 by applying the following rules iteratively:
  1. If n is even, divide it by 2 (n = n // 2).
  2. If n is odd, multiply it by 3 and add 1 (n = 3n + 1).
The goal is to see how many steps it takes for the starting number to reach 1 by applying these rules repeatedly.

The for loop will run up to 50000 times or until the number becomes 1, whichever comes first. This is done to avoid infinite loops in case the Collatz conjecture fails for some starting numbers.

Python:
if number == 1:
    break

If the number becomes 1, we break out of the loop since we have reached the target value.

Python:
elif number % 2 == 0:
    number // 2 == number
    steps = steps + 1

If the number is even, we apply the rule n = n // 2, which divides the number by 2. Then, we increment the steps counter by 1.

Python:
elif number % 2 != 0:
    number = number * 3 + 1
    steps = steps + 1

If the number is odd, we apply the rule n = 3n + 1, which multiplies the number by 3 and adds 1. Then, we increment the steps counter by 1.


Finally, after the loop ends, the code checks if the number has become 1. If so, it prints the number of steps it took to reach 1; otherwise, it prints that the number didn't reach 1 yet.

To test the Collatz conjecture for a specific number (in this case, 27), you can run this code and see the number of steps it takes to reach 1. Keep in mind that for some very large starting numbers, the process might take a long time to complete or the code may not terminate within 50000 steps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,069
Latest member
SimplyleanKetoReviews

Latest Threads

Top