Bonjour, mes amis! Today, we’re plunging headfirst into the mathematical deep end, but don’t worry, we’ve got inflatable flamingos. We’re talking about the Suite de Syracuse, also known as the Collatz Conjecture, the 3n+1 problem, or, as I like to call it, “that thing that keeps mathematicians up at night.” And, because we’re modern and sophisticated (or at least, we try to be), we’re going to tackle it with Python. Python, mon amour!
The Enigmatic Suite de Syracuse: A Mathematical Soap Opera
Imagine a mathematical sequence so simple, even your cat could understand it (though your cat would probably prefer to nap). That’s the Suite de Syracuse. Here’s the lowdown:
- Start with any positive integer, let’s call it ‘n’.
- If ‘n’ is even, divide it by 2 (n / 2).
- If ‘n’ is odd, multiply it by 3 and add 1 (3n + 1).
- Repeat. Forever. Or until your computer crashes, whichever comes first.
The Collatz Conjecture states that no matter what number you start with, you’ll always eventually reach 1. Always! It’s like a mathematical black hole, sucking in numbers and spitting them out as… well, 1. Sounds simple, right? Ha! Mathematicians have been trying to prove this for decades. It’s the mathematical equivalent of trying to herd cats. Good luck with that!
Now, I know what you’re thinking: “This sounds utterly pointless.” And you know what? Maybe it is! But it’s gloriously pointless. It’s the kind of problem that makes you question the fabric of reality, all while providing endless amusement. And that, mes amis, is why we love it.
Why Bother with This Nonsense?
Besides the sheer intellectual thrill of contemplating the abyss of unsolved mathematical problems (which, let’s be honest, is a pretty good reason), exploring the Suite de Syracuse is a fantastic way to learn about:
- Loops: Because you’ll be repeating those calculations until the cows come home (or, you know, until you reach 1).
- Conditional Statements: The very essence of “if this, then that” logic. It’s like teaching your computer to play “Would You Rather?” but with numbers.
- Functions: Encapsulating your Syracuse calculations into a neat, reusable package. Because who wants to write the same code over and over? Certainly not me!
- List Comprehensions (Bonus!): For when you’re feeling fancy and want to generate sequences with a single, elegant line of code. Think of it as the haute couture of Python programming.
So, grab your keyboard, pour yourself a glass of wine (or a cup of coffee, if you’re feeling particularly virtuous), and let’s dive into the wonderful world of the Suite de Syracuse with Python!
Python to the Rescue! (or, at Least, to Calculate)
Okay, enough preamble. Let’s get our hands dirty with some code. We’re going to write a Python function that calculates the Syracuse sequence for a given starting number.
def syracuse(n):
"""
Calculates the Syracuse sequence for a given starting number.
Args:
n: The starting positive integer.
Returns:
A list containing the Syracuse sequence starting with n and ending with 1.
"""
sequence = [n]
while n != 1:
if n % 2 == 0:
n = n // 2 # Integer division, because we're classy.
else:
n = 3 * n + 1
sequence.append(n)
return sequence
Let’s break down this masterpiece of code, shall we?
- `def syracuse(n):`: This defines our function, aptly named `syracuse`, which takes one argument, `n`, the starting number.
- `”””Docstring”””`: This is a docstring, a fancy way of saying “comments for grown-ups.” It explains what the function does, its arguments, and what it returns. It’s like leaving a trail of breadcrumbs for your future self (or anyone else who dares to read your code).
- `sequence = [n]`: We initialize a list called `sequence` with our starting number. This list will store the entire Syracuse sequence.
- `while n != 1:`: This is the main loop. It keeps running as long as our current number `n` is not equal to 1.
- `if n % 2 == 0:`: This checks if `n` is even. The `%` operator gives us the remainder after division. If the remainder is 0 when divided by 2, then `n` is even.
- `n = n // 2`: If `n` is even, we divide it by 2. Note the `//` operator, which performs integer division (i.e., it throws away any fractional part). We don’t want no floating-point shenanigans here!
- `else:`: If `n` is not even (i.e., it’s odd), we execute the `else` block.
- `n = 3 * n + 1`: We multiply `n` by 3 and add 1. This is the heart of the Syracuse sequence.
- `sequence.append(n)`: We add the new value of `n` to our `sequence` list.
- `return sequence`: Once the loop finishes (i.e., when `n` reaches 1), we return the entire `sequence` list.
Now, let’s try it out!

print(syracuse(10))
# Output: [10, 5, 16, 8, 4, 2, 1]
print(syracuse(7))
# Output: [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Voila! We have successfully calculated the Syracuse sequence for 10 and 7. Notice how the sequence for 7 is much longer than the sequence for 10. That’s the beauty (and the terror) of the Collatz Conjecture: you never know how long it will take to reach 1.
Adding a Touch of Flair: List Comprehensions
For those of you who like to show off (and who doesn’t?), we can rewrite the `syracuse` function using a list comprehension. It’s like saying the same thing, but in a much more stylish way.
def syracuse_comprehension(n):
"""
Calculates the Syracuse sequence using a list comprehension.
Args:
n: The starting positive integer.
Returns:
A list containing the Syracuse sequence starting with n and ending with 1.
"""
sequence = [n]
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
sequence.append(n)
return sequence
See that line `n = n // 2 if n % 2 == 0 else 3 * n + 1`? That’s a conditional expression, also known as a ternary operator. It’s a shorthand way of writing an `if-else` statement in a single line. It reads: “If `n` is even, then `n = n // 2`, otherwise, `n = 3 * n + 1`.” It’s like a tiny, elegant poem of code.
The result is the same, but the code is more concise. Use it wisely, young padawan. Too much brevity can lead to unreadable code. But in this case, it’s just the right amount of “ooh la la!”
Visualizing the Madness: Plotting the Sequences
Now that we can calculate Syracuse sequences, let’s make them pretty! We’re going to use the `matplotlib` library to plot the sequences and visualize their behavior. If you don’t have `matplotlib` installed, you can install it using pip:
pip install matplotlib
Here’s the code to plot the Syracuse sequence for a given starting number:

import matplotlib.pyplot as plt
def plot_syracuse(n):
"""
Calculates and plots the Syracuse sequence for a given starting number.
Args:
n: The starting positive integer.
"""
sequence = syracuse(n) # Use our previously defined function!
plt.plot(sequence)
plt.xlabel("Step")
plt.ylabel("Value")
plt.title(f"Syracuse Sequence for n = {n}")
plt.grid(True)
plt.show()
plot_syracuse(10)
plot_syracuse(7)
plot_syracuse(27) # Prepare for a wild ride!
This code does the following:
- `import matplotlib.pyplot as plt`: This imports the `matplotlib.pyplot` module and gives it the alias `plt`. It’s like calling your friend “Bob” instead of “Robert.” Saves time, you know?
- `def plot_syracuse(n):`: This defines a new function called `plot_syracuse` that takes the starting number `n` as an argument.
- `sequence = syracuse(n)`: We use our `syracuse` function (the one we defined earlier!) to calculate the Syracuse sequence for `n`.
- `plt.plot(sequence)`: This plots the sequence. The x-axis represents the step number, and the y-axis represents the value of the number in the sequence.
- `plt.xlabel(“Step”)`, `plt.ylabel(“Value”)`, `plt.title(…)`: These lines add labels to the x-axis, y-axis, and the title of the plot, respectively. It’s like giving your plot a proper name and a nice outfit.
- `plt.grid(True)`: This adds a grid to the plot, making it easier to read the values. Because, you know, we’re all about readability.
- `plt.show()`: This displays the plot. The moment of truth!
Try running this code with different starting numbers. You’ll see that some sequences are short and sweet, while others are long and winding, like a bad romance novel. Pay special attention to the sequence for 27. It’s a real rollercoaster!
The Infamous Case of Number 27
Speaking of number 27, it’s a notorious example in the world of the Collatz Conjecture. Its sequence takes a whopping 111 steps to reach 1, and it climbs to a dizzying peak of 9232 before plummeting back down. It’s like the Mount Everest of Syracuse sequences. If you plot the sequence for 27, you’ll see a chaotic mess of lines, a testament to the unpredictable nature of this seemingly simple problem. It’s a good example of how something can be easy to explain, yet difficult to predict. Think of it as the weather forecast, but for numbers!
Going Further: Exploring the Conjecture
Now that you’ve mastered the basics, let’s explore some more advanced concepts and challenges related to the Collatz Conjecture.
Finding the Longest Sequence Below a Certain Number
One interesting problem is to find the starting number below a certain limit that produces the longest Syracuse sequence. This is like searching for the longest road trip you can take without ever leaving a particular state.
def longest_syracuse_sequence(limit):
"""
Finds the starting number below a given limit that produces the longest Syracuse sequence.
Args:
limit: The upper limit for the starting number.
Returns:
A tuple containing the starting number and the length of its Syracuse sequence.
"""
longest_length = 0
longest_number = 0
for i in range(1, limit):
length = len(syracuse(i))
if length > longest_length:
longest_length = length
longest_number = i
return longest_number, longest_length
number, length = longest_syracuse_sequence(1000)
print(f"The longest Syracuse sequence below 1000 starts with {number} and has a length of {length}.")
This code iterates through all the numbers from 1 to `limit`, calculates the length of their Syracuse sequences, and keeps track of the number with the longest sequence. It’s a brute-force approach, but it works! (And sometimes, brute force is all you need.)

Caching for Speed: Memoization
If you’re calculating a lot of Syracuse sequences, you’ll notice that you’re often recalculating the same values over and over. For example, the sequence for 10 includes the sequence for 5, and the sequence for 16 includes the sequence for 8, and so on. This is where caching comes in handy. Caching is a technique where you store the results of expensive calculations so that you can reuse them later without having to recalculate them. Think of it as having a cheat sheet for math class, but perfectly legal!
In Python, we can use a dictionary to implement a simple cache.
cache = {} # Our empty cache!
def syracuse_cached(n):
"""
Calculates the Syracuse sequence using caching.
Args:
n: The starting positive integer.
Returns:
A list containing the Syracuse sequence starting with n and ending with 1.
"""
if n in cache:
return cache[n]
sequence = [n]
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
sequence.append(n)
cache[n] = sequence # Store the result in the cache!
return sequence
This code first checks if the result for `n` is already in the cache. If it is, it simply returns the cached result. Otherwise, it calculates the sequence as before, but before returning it, it stores the result in the cache. This can significantly speed up calculations, especially when dealing with large numbers and many sequences.
Visualizing Sequence Lengths: A Heatmap
Another interesting visualization is a heatmap of Syracuse sequence lengths. This allows you to see how the sequence lengths vary across a range of starting numbers.
import numpy as np
def syracuse_lengths_heatmap(limit):
"""
Generates a heatmap of Syracuse sequence lengths for numbers below a given limit.
Args:
limit: The upper limit for the starting numbers.
"""
lengths = np.zeros((limit, limit))
for i in range(1, limit):
sequence = syracuse(i)
lengths[i-1, :len(sequence)] = len(sequence) #Store the sequence length for each number
plt.imshow(lengths, cmap='hot', interpolation='nearest')
plt.colorbar(label='Sequence Length')
plt.xlabel("Step")
plt.ylabel("Starting Number")
plt.title("Heatmap of Syracuse Sequence Lengths")
plt.show()
syracuse_lengths_heatmap(100)
This code creates a 2D array (using `numpy`) to store the sequence lengths. It then iterates through all the numbers from 1 to `limit`, calculates their Syracuse sequences, and stores the length of each sequence in the array. Finally, it uses `plt.imshow` to display the array as a heatmap, where the color of each cell represents the sequence length. The `hot` colormap provides a nice visual representation, with longer sequences appearing as brighter colors.
The Unsolved Mystery: Why Does It Work? (Or Does It?)
Despite all our calculations and visualizations, the fundamental question remains: why does the Collatz Conjecture seem to hold true? Why do all numbers eventually converge to 1? Mathematicians have been scratching their heads over this for decades, and no one has come up with a definitive proof (or a counterexample, for that matter). There are many theories and partial results, but the full picture remains elusive.

Some speculate that the conjecture is true because the division by 2 tends to shrink the numbers, while the multiplication by 3 and addition of 1 tends to increase them. However, on average, the division by 2 dominates, leading to a gradual decrease towards 1. But this is just a heuristic argument, not a rigorous proof.
Others have explored the conjecture using probabilistic methods, arguing that the random-like behavior of the sequence makes it highly likely that all numbers will eventually reach 1. But again, this is not a proof. The Collatz Conjecture remains one of the most perplexing and fascinating unsolved problems in mathematics.
The Moral of the Story (and a Pythonic Twist)
So, what have we learned today? We’ve learned that the Suite de Syracuse is a deceptively simple mathematical sequence that has baffled mathematicians for decades. We’ve learned how to calculate Syracuse sequences using Python, how to visualize them, and how to explore some related problems. And we’ve learned that even seemingly simple problems can hide deep and mysterious complexities.
But perhaps the most important lesson is that even if we don’t have all the answers, we can still have fun exploring the unknown. The Suite de Syracuse is a reminder that mathematics is not just about finding the right answers, but also about asking the right questions. And who knows, maybe one day you’ll be the one to crack the Collatz Conjecture and earn your place in mathematical history.
In the meantime, keep coding, keep exploring, and keep questioning. And remember, la vie est belle, even when you’re wrestling with unsolved mathematical problems. Especially when you’re wrestling with unsolved mathematical problems… with Python!
A Final Pythonic Thought (and a Pun!)
The Collatz Conjecture is a bit like debugging Python code. You start with a seemingly simple piece of code, and then suddenly you’re chasing down endless loops and unexpected results. But eventually, you find the bug, and everything works as expected (or at least, that’s the hope!). So, keep your chin up, keep debugging, and remember: “Collatz later!” (Get it? Collatz… catches… never mind.)




![[Python 3.X] Programme sur la conjecture de Syracuse](http://www.developpez.net/forums/attachments/p159831d1414332706/autres-langages/python-zope/general-python/programme-conjecture-syracuse/capture-d-e-cran-2014-10-26-15.10.24.png/)









![Suite de Syracuse sur python (Graph) [15 réponses] : Lycée - 215097](https://i.imgur.com/vQeBuSs.png)