FizzBuzz

Easy · rating 1000 · implementation, math

Read an integer n. For each i from 1 to n, print Fizz if i is divisible by 3, Buzz if divisible by 5, FizzBuzz if divisible by both, otherwise the number itself — one per line.

Constraints: 1 ≤ n ≤ 10000

Editorial

Approach

Loop from 1 to n. The only subtlety is order: a number divisible by both 3 and 5 (i.e. by 15) must print FizzBuzz. The cleanest way to guarantee that is to build the output by string concatenation — append Fizz when divisible by 3 and Buzz when divisible by 5 — which handles the combined case for free.

for i in range(1, n+1):
    out = ''
    if i % 3 == 0: out += 'Fizz'
    if i % 5 == 0: out += 'Buzz'
    print(out or i)

Complexity

Time: O(n). Space: O(1).

Open FizzBuzz in Code Arena →