4 Billion If Statements: When Absurdity Becomes Interesting
I recently came across an article by Andreas Karlsson called “4 billion if statements” [Karlsson, 2023] and I just had to share it. It’s a delightful journey into the absurd that actually reveals something deeper about problem-solving and computer science.
The Original Joke
The article starts with a screenshot that was circulating on TikTok. A beginner programmer, tasked with checking if a number is odd or even, wrote something like this instead of using the modulo operator:
if number == 0:
print("even")
if number == 1:
print("odd")
if number == 2:
print("even")
if number == 3:
print("odd")
# ... and so on The internet, of course, responded with the usual cascade of snarky comments about this “fresh programmer’s” approach.
But What If We Actually Did It?
Here’s where the article gets interesting. Instead of dismissing the approach, Karlsson asks: what if we actually took this to its logical extreme? What would happen if we genuinely tried to check every possible 32-bit integer this way, requiring 4 billion if statements?
This is the kind of question that turns a joke into a learning experience.
Hitting Real-World Limitations
The journey to create this absurd program hits fascinating obstacles:
Compiler limits: The Microsoft C compiler ran out of heap space trying to process a 330GB source file with over 130 million lines.
File format limits: The Windows executable format (.exe) can’t handle files larger than 4GB, and with 4 billion comparisons, even one byte per comparison would exceed that.
Time constraints: Generating the source code alone took 48 hours.
Creative Problem-Solving
Faced with these limitations, Karlsson gets creative. If the compiler won’t help, write the machine code directly! The final solution:
- Uses Python to generate raw x86-64 machine code
- Memory-maps a 40GB binary file containing all 4 billion comparisons
- Actually works and returns results in about 10 seconds for the largest numbers
Why This Matters
This article resonated with me because it demonstrates something important about how we approach problems. Even when a problem seems nonsensical or impossible, the act of trying to solve it can reveal:
- Hidden assumptions we make about our tools
- Real limitations of the systems we use
- Creative workarounds that push our understanding
It’s a reminder that sometimes the journey of attempting something “impossible” teaches us more than taking the obvious path.
The Takeaway
Next time you see something that seems obviously wrong or inefficient, consider: what would happen if you actually tried it? You might not end up with a practical solution, but you’ll probably learn something interesting along the way.
The original article is a fantastic read with all the technical details. I highly recommend checking it out!
References
- Karlsson, Andreas (2023). 4 billion if statements. Blabbin'. Link