Fizz Buzz Implementation | Set 2
Given an integer N, the task is to print all the numbers from 1 to N replacing the multiples of 3, 5 and both 3 and 5 by “Fizz”, “Buzz” and “Fizz Buzz” respectively.
Input: N = 5
Output: 1, 2, Fizz, 4, Buzz
Input: N = 15
Output: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14
- Modulo operator is a very expensive operation. In the lowest level, modulo is a division.
- The DIV instruction of the compiler gives the division and modulo results. However, modern CPUs use specialized division circuits with lookup tables and so, there won’t be any significant change in speed by using bit-shifting.
- But for large integers, it is observed that the runtime is much slower in the modulo operation program than the other, with O(N2) computational complexity.
Follow the below steps to solve the problem:
- Initialize two count variables, say count3 and count5, to store the count of numbers divisible by 3 and 5 respectively.
- Iterate over the range [1, N] using a variable, say i, and perform the following steps:
- Increment count3 and count5 by 1.
- If the value of count3 is equal to 3, print “Fizz” and set count3 = 0.
- Similarly, if the value of count5 is equal to 5, print “Buzz” and set count5 = 0.
- If none of the above conditions match, then print i.
Below is the implementation of the above approach:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.