import solara
import matplotlib.pyplot as plt
import networkx as nx
def collatz_sequence(n):
sequence = [n]
while n!=1:
if n%2==0:
n=n//2
else:
n=3*n+1
sequence.append(n)
return sequence
def collatz_tree(n):
G = nx.DiGraph()
G.add_node(n)
nodes = [n]
while nodes:
current = nodes.pop(0)
if current!=1:
if current%2==0:
next_num=current//2
else:
next_num =3 * current + 1
G.add_node(next_num)
G.add_edge(current, next_num)
nodes.append(next_num)
return G
def plot_collatz(n):
sequence = collatz_sequence(n)
plt.figure(figsize=(10, 6))
plt.plot(sequence, marker='o')
plt.title(f'Collatz Conjecture Sequence for {n}')
plt.xlabel('Step')
plt.ylabel('Value')
plt.grid(True)
plt.xticks(range(len(sequence)))
plt.show()
def hierarchical_layout(G, root):
pos = {}
level = 0
next_level_nodes = [root]
while next_level_nodes:
current_level_nodes = next_level_nodes
next_level_nodes = []
for i, node in enumerate(current_level_nodes):
pos[node] = (i, -level)
next_level_nodes.extend(G.successors(node))
level += 1
return pos
def plot_collatz_tree(n):
G = collatz_tree(n)
pos = nx.spring_layout(G)
plt.figure(figsize=(12, 8))
nx.draw(G, pos, with_labels=True, node_size=500, node_color="lightblue", font_size=10, font_weight="bold", arrowsize=20)
plt.title(f'Collatz Conjecture Tree for {n}')
plt.show()
@solara.component
def Page():
int_value = solara.reactive(42)
continuous_update = solara.reactive(True)
solara.InputInt("Enter an integer number", value=int_value, continuous_update=continuous_update.value)
plot_collatz(int_value.value)
plot_collatz_tree(int_value.value)