Collatz 2

#!/usr/bin/python # Program to calculate the Collatz of each number from 1 to n import math import time def collatz(n, cg): if n in cg: return if math.log(n, 2)==int(math.log(n, 2)): cg[n]= [int(2**(math.log(n,2)-1)), int(math.log(n, 2))] collatz(2**(math.log(n,2)-1), cg) return else: if n%2: c= 3*n+1 else: c= n/2 collatz(c, cg) cg[n]= [c, cg[c][1]+1] return def calc_cycle(n): collatz_graph= {1: [None, 0]} for i in range(2,n+1): if i not in collatz_graph: collatz(i, collatz_graph) return collatz_graph
Makes a graph of collatz numbers between 1 & n, with each number pointing to the next number in line, and it also calculates the size of the cycle of each number

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.