2

I've been trying to write a python script to make a graph of the iterations it takes for a number to go through the collatz conjecture. In this example I only used a very small range (Only the number 1) but this script seems to keep running and will not produce a graph even after being run for 10 minutes. Below is the code. Any advice?

import math
import matplotlib.pyplot as plt

def collatz(x):
    count = 0
    while x != 1:   
        if x % 2 == 0:
            x=x/2
            count=count+1
        else:
            x=(x*3)+1
            count=count+1
    return count 
x_coordinates = []
y_coordinates = []
for i in range(0, 2):
    x_coordinates.append(i)
    y = collatz(i)
    y_coordinates.append(y)

plt.plot(x_coordinates, y_coordinates)
plt.show()

1 Answers1

2

so you start your iteration with y = collatz(0), so x==0 and you enter the while x != 1 loop, right?

now what happens to the if clause?

if 0 % 2 == 0:
    x = 0/2 # == 0

so x never becomes 1 and you keep running the while loop forever, don't you?

if you're referring to that Collatz problem, then you should re-read the statement carefully:

Does the Collatz sequence from initial value n eventually reach 1, for all n > 0?

Pavel
  • 7,436
  • 2
  • 29
  • 42