Python SolutionsPython Solutions
📉
Collatz Conjecture
Week 16, 2026
All SolutionsPython - Pillow Lib + collatzConjecture function | BMC | Python Solutions
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")
python | devilssnare | Python Solutions
from PIL import Image
WIDTH = 1000
HEIGHT = 1000
LIMIT = WIDTH * HEIGHT
img = Image.new("RGB", (WIDTH, HEIGHT))
pixels = img.load()
def collatz_pixel(n: int):
x = n
even_count = 0
odd_count = 0
max_value = x
if x == 1:
seq = [1, 4, 2, 1]
even_count = sum(1 for v in seq if v % 2 == 0)
odd_count = sum(1 for v in seq if v % 2 == 1)
max_value = max(seq)
else:
while True:
if x % 2 == 0:
even_count += 1
x //= 2
else:
odd_count += 1
x = 3 * x + 1 if x != 1 else 1
if x > max_value:
max_value = x
if x == 1:
odd_count += 1
break
r = min(even_count, 255)
g = min(odd_count, 255)
b = min(max_value // n, 255)
return (r, g, b)
for n in range(1, LIMIT + 1):
px = (n - 1) % WIDTH
py = (n - 1) // WIDTH
pixels[px, py] = collatz_pixel(n)
img.save("collatz.png", "PNG")
print("Saved image")