The Collatz's Conjecture states that any number can either be halved (if it is even) or multiplied by three and added one to (if it is odd) and eventually reach 1.
I was wondering if there was a more efficient way to work out the series that a number takes to get to one and the amount of steps it takes. The Python (3.x) code is:
i, k = 1, 1 fh=open("results.txt", "w") print("Started") def colapatz(x): seq = [x] j = 0 while x > 1: if x % 2 == 0: x = x / 2 j = j + 1 else: x = 3 * x + 1 j = j + 1 seq.append(x) fh.write("Value number " + str(i) + " takes "+ str(j) + " steps.\n") fh.write("It takes the sequence: " + str(seq) + "\n") #Call the function while k<10000: k+=1 i+=1 colapatz(i) print("Finished") fh.close()
The is one of my first python programs that I've ever written, so any improvements would be great.