- Collatz Conjecture (The Math)
- Collatz Conjecture (The Code)
In the
def collatz(n): if n == 1: return 1 elif n % 2 == 0: return n / 2 else: return (3 * n) + 1
This program just returns the value for a single value so we need to wirte an extra function to get the sequence:
def colseq(n): a = [] a.append(int(n)) while n != 1: n = collatz(n) a.append(int(n)) print(a)
The code above adds the values in the sequence to an array and then prints simply prints the array to the screen, running the code above produces the following output:
>>> colseq(20) [20, 10, 5, 16, 8, 4, 2, 1]
This has just been a small project, i plan to do more in the future, but I just wanted to get something on this website, so wanted to share something which I have gotten back into i.e. Mathematics and Programming.