FizzBuzz: An intermezzo

Scaring myself with the revelation that many would-be developers ostensibly cannot write FizzBuzz, I became anxious to know if I would pass the test. The task is to write a program in as few characters as possible that will print the numbers 1 to 100 each on a new line, except multiples of 3 become "Fizz," multiples of 5 are "Buzz," and multiples of both 3 and 5 are "FizzBuzz." As it turns out, the solution is nice and short in Kotlin:

fun main() {
    for (i in 1..100) {
        println(when {
            i % 3 == 0 && i % 5 == 0 -> "FizzBuzz"
            i % 3 == 0 -> "Fizz"
            i % 5 == 0 -> "Buzz"
            else -> i

The overall logic is simple enough, just a plain old loop through 1 to 100 and conditionals to determine what to print. But I had to think for a second to remember the modulus operator... Here it means that when i is divided by either 3 or 5 and the remainder is 0, then it is a multiple of 3 or 5. I wonder if there's an even more concise way to do this.

The when conditional makes things neat, instead of nested if/else if statements. i % 3 == 0 && i % 5 == 0 needs to come first, or else the program will print "Fizz" as long as i is a multiple of 3, regardless of whether it is also a multiple of 5. And so on. Another thing is that if i weren't pressed for characters, I would maybe write "$i" in that else branch instead of just i to be consistent with the preceding branches, which all result in strings. But this appears to be a non-issue.

Related posts