dark mode light mode Search Menu
Search

FizzBuzz

CollegeDegrees360 on Flickr

Your challenge is to print out a list of numbers from 1 to 100. Every number divisible by 3 must be replaced by the word ‘fizz’, and every number divisible by 5 is replaced by ‘buzz’. If the number is divisible by both 3 and 5, then replace it with ‘fizzbuzz’.

It’s a simple problem with many solutions, from the quick and easy to the complex and elegant. In computer geek circles, ‘FizzBuzz’ is a classic puzzle that pops up time and time again. Companies even ask it to candidates during coding interviews!

Take a moment and think about how you’d approach the code. What hurdles could you hit? What coding structures can you pull out of your arsenal?

A SIMPLE SOLUTION

The piece of code that makes things simple is the modulus operator, which you write as “%” and say out loud as “mod”. It’s a mathematical operator, like +, -, or *, and it tells us how much is leftover after a division.

Remember how we did divisions before learning about decimal numbers? So if:

15 / 6 == 2 (with a of remainder 3)
THEN
15 % 6 == 3

Likewise:

7 / 3 == 2 (with a of remainder 1)
THEN
7 % 3 == 1

When a number is perfectly divisible by another, then the mod operator always returns 0.

9 / 3 == 3 (no remainder)
SO
9 % 3 == 0

Likewise:

10 / 5 == 2 (no remainder)
SO
10 % 5 == 0

As a rule of thumb, when you need to check divisibility in a program, use the modulus operator!

Now, let’s take a look at this simple solution to FizzBuzz, written in Python:

for num in xrange(1, 101): # for all numbers from 1 to 100
    if num % 3 == 0 and num % 5 == 0:
        print("fizzbuzz")
    elif num % 3 == 0:
        print("fizz")
    elif num % 5 == 0:
        print("buzz")
    else:
        print(num)

Try it out for yourself! You can download a free IDE like PyCharm or use an online website like repl.it to run the code.

In our program, we loop through all the numbers between 1 and 100. For each number, we check if it’s divisible by both 3 and 5, in which case we print ‘fizzbuzz’. Next, we cover the cases where it’s only divisible by one number. Finally, our “catch all” else statement handles the numbers that are divisible by neither 3 nor 5, which are printed normally.

Our code does the job — but does it do it well?

BEST PRACTICES

Code can be judged on three criteria:

  1. EASY TO READ. If someone is unfamiliar with our program, how easy is it to read and understand?
  2. SPEED. Are there any unnecessary operations? Do we repeat things we don’t have to?
  3. FLEXIBILITY. If we want to modify our program, how easy is it to add or remove features?

Our FizzBuzz program is definitely easy to read. In terms of efficiency, there’s a few tweaks that will make it faster. For example, the same mod operation is done multiple times. What if we combine them?

for num in xrange(1, 101): # for all numbers from 1 to 100
   fizz = (num % 3 == 0)
   buzz = (num % 5 == 0)
   output = ""
   if fizz:
       output += "fizz"
   if buzz:
       output += "buzz"
   if output == "":
       output = num
   print(output)

On the plus side, our operations no longer repeat, but on the down side, the code is morphing into something obscure and bizarre. Is the second snippet better? This isn’t a universal “yes or no” answer; it depends on the goal of your software. If you’re writing code for an embedded microchip, you probably want the faster program. If you have a large software base where hundreds of developers sift through thousands of lines of code, you might prefer the version that’s easier to understand.

Then there’s our third criteria — flexibility. What if we want to print out numbers up to 500? What if we want a third divisor — a “bang”, or a “zazz”, that replaces every number divisible by 7?

In the non-existent world of perfect software, your program should easily handle these changes, perhaps even with the modification of a single line of code. In our case, we’d need to start messing around with data structures like lists and dictionaries, which will make our code more complex.

At the end of the day, there’s no single solution to FizzBuzz. Figuring out different ways to solve a problem is part of the joy of programming. If you feel overwhelmed, just remember the golden rule: get your code done, get it working, and worry about the rest later. Above all, have fun!

Learn More

About the modulus operator

https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic

A detailed article about FizzBuzz

https://www.tomdalling.com/blog/software-design/fizzbuzz-in-too-much-detail/

Twenty Ways to Fizz Buzz

https://ditam.github.io/posts/fizzbuzz/

A complex mathematical solution to FizzBuzz

https://read.klipse.tech/the-most-elegant-implementation-of-fizzbuzz/