[Python] Python - Pillow Lib + collatzConjecture function[Python] Python - Pillow Lib + collatzConjecture function
📉
Collatz Conjecture
Week 16, 2026
from PIL import Image
def collatzConjecture(n:int, row:int, col:int) -> None:
evenCount = 0
oddCount = 0
maxNum = n
startNum = n
while n > 1:
if n > maxNum: maxNum = n
if n % 2 == 0:
evenCount += 1
n //= 2
else:
oddCount += 1
n = n*3 + 1
oddCount += 1 # inc by 1 because of n
maxNumQ = maxNum // startNum
if startNum == 1: # special case because of 1
evenCount += 2
oddCount += 1
maxNumQ += 3
setPixelValue(evenCount, oddCount, maxNumQ, row, col)
def setPixelValue(
evenCount :int,
oddCount :int,
maxNumQ :int,
row :int,
col :int
) -> None:
global ans
r = evenCount if evenCount < 255 else 255
g = oddCount if oddCount < 255 else 255
b = maxNumQ if maxNumQ < 255 else 255
ans[row][col] = (r, g, b)
def makeFinalImage(someArray: list) -> None:
global ROWS, COLS
flat_data = [pixel for row in someArray for pixel in row]
img = Image.new('RGB', (COLS, ROWS))
img.putdata(flat_data)
img.save('ans1.png')
# -- main --
ROWS = 1000
COLS = 1000
n = 1
ans = [[(0,0,0) for col in range(COLS)] for row in range(ROWS)]
for row in range(ROWS):
for col in range(COLS):
collatzConjecture(n, row, col)
n += 1
if n % 1000 == 0:
print(f"{n/(ROWS*COLS) * 100}% completed...")
print(f"REACHED : {n}")
print("\n -- PROCESS COMPLETED -- \n")
makeFinalImage(ans)
print("\n -- IMAGE MADE -- \n")