Algorithm LogbookAlgorithm Logbook

The Modular Operator

Basic Math

๐Ÿ“‹ Problem Statement

Write a program that prints the numbers from 1 to 100. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".

๐Ÿ’ก Intuition

This problem tests your understanding of the modular operator (โ€Šmodโ€Š\bmod) and control flow. The key insight is that you need to handle the most specific condition (divisible by both 3 AND 5) correctly. Instead of checking divisibility by 15 first, you can build the output string incrementally โ€” append "Fizz" if nโ€Šmodโ€Š3=0n \bmod 3 = 0, then append "Buzz" if nโ€Šmodโ€Š5=0n \bmod 5 = 0. This naturally produces "FizzBuzz" for multiples of both.

๐Ÿ”ง Approach

  1. Loop through numbers 1 to 100.
  2. For each number, initialize an empty string.
  3. If nโ€Šmodโ€Š3=0n \bmod 3 = 0, append "Fizz" to the string.
  4. If nโ€Šmodโ€Š5=0n \bmod 5 = 0, append "Buzz" to the string.
  5. If the string is still empty (not divisible by 3 or 5), print the number itself.
  6. Otherwise, print the constructed string.

โšก Complexity Analysis

Time

O(N)O(N) where NN is the range of numbers (100 in this case)

Space

O(1)O(1) โ€” only a single output string variable is used

โš ๏ธ Common Mistakes

  • Checking divisibility by 3 before checking for both 3 and 5, which causes "FizzBuzz" cases to print only "Fizz"
  • Using elif instead of separate if statements when building the string incrementally
  • Forgetting that 0โ€Šmodโ€Š3=00 \bmod 3 = 0 is true, so starting from 0 instead of 1 gives an extra empty output

๐ŸŽฏ Final Thoughts

FizzBuzz is a classic interview warm-up that tests basic control flow and the modular operator. The string-building approach is more elegant than checking for 15 first, and it scales better if more conditions are added (e.g., "Jazz" for multiples of 7).