Satyam Tripathi

Fizz Buzz Program

The FizzBuzz problem, a common coding exercise, involves iterating from 1 to n. For each integer, print “Fizz” if it’s a multiple of 3, “Buzz” if a multiple of 5, “FizzBuzz” if divisible by both 3 and 5, and the number itself if none of these conditions apply. Creating a FizzBuzz program efficiently handles these rules and outputs the desired results.

Problem Statement

The FizzBuzz Problem states that we are given a number n and we iterate from 1 to n, both inclusive. It has a particular set of conditions, i.e.,

  • Print Fizz in place of the given integer if it is a multiple of 3.
  • Print Buzz in place of the given integer if it is a multiple of 5.
  • Print FizzBuzz in place of that number if it is a multiple of 3 and 5.
  • If none of the above conditions are satisfied, then we will print the number.

In this way, we execute the FizzBuzz program.

Example

Input

6

Output

[1, 2, 'Fizz', 4, 'Buzz', 'Fizz']

Example Explanation

In the above fizzbuzz program, we can see that the input given to us, i.e., n, is 6. Therefore, we iterate from numbers 1 to 6.

Therefore,

  • 1 is not a multiple of 3 or 5, so we simply print the number 1.
  • 2 is not a multiple of 3 or 5, so we simply print the number 2.
  • 3 is a multiple of 3, not a multiple of 5, so we print Fizz.
  • 4 is not a multiple of 3 or 5, so we simply print the number 4.
  • 5 is a multiple of 5, so we print Buzz.
  • 6 is a multiple of 3, so we print Fizz.

Therefore, in this way, we get the desired output in the FizzBuzz program.

Constraints

The constraints can vary according to the approach and optimization technique. But the general constraints of fizzbuzz program apply to the size of n, i.e.,

1 <= n <= 104104

Therefore, this is the constraint or the range for the input n.

Approach 1: Using Modulus Operation

This is the simplest and easiest way to solve the FizzBuzz program. It tells us to run a loop from 1 to n and use the modulus operator to check the following conditions. Firstly, inside the for loop, we write the condition for checking the divisibility of both 3 and 5. After that, we check for singular modules, i.e., 3 and 5, and print the outputs accordingly. If any of the 3 conditions are not satisfied, we print the number.

  • Algorithm:
    • We run a loop from 1 to n (inclusive) and check for each number.
    • Check if the number is divisible by 3 and 5 both. If true, then print FizzBuzz
    • Check if the number is divisible by 3. If true, print Fizz
    • Check if the number is divisible by 5. If true, print Buzz
    • If none of the above conditions is true, we can only print the number.

The above discussed points are the algorithm for the basic or naive approach to the FizzBuzz problem statement.

Code:

Python

n = int(input())
for i in range(1, n+1):
    if (i % 15 == 0):
        print("FizzBuzz")
    elif (i % 3 == 0):
        print("Fizz")
    elif(i % 5 == 0):
        print("Buzz")
    else:
        print(i)

C++

#include <iostream>
using namespace std;

int main(){
    int n;
    cin >> n;
    for (int i = 1; i < n + 1; i++){
        if (i % 15 == 0)
            cout << "FizzBuzz" << endl;
        else if (i % 3 == 0)
            cout << "Fizz" << endl;
        else if (i % 5 == 0)
            cout << "Buzz" << endl;
        else
            cout << i << endl;
    }
    return 0;
}

Java

import java.util.*;

class Approach1 {

  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    for (int i = 1; i <= n; ++i) {
      if (i % 15 == 0) 
          System.out.println("FizzBuzz"); 
      else if (i % 3 == 0) 
          System.out.println("Fizz"); 
      else if (i % 5 == 0) 
          System.out.println("Buzz"); 
      else 
          System.out.println(i);
    }
  }
}

Output:

Input: N = 6 Output:

1
2
Fizz
4
Buzz
Fizz
  • Time Complexity:In the above fizzbuzz program naive modulus approach, we run only a single for loop. The time complexity of the solution is O(n).
  • Space Complexity:In the above fizzbuzz program naive modulus approach, we do not use any extra space. Therefore, the total space complexity of the above logic is O(1).

Approach 2: Without Using Modulus Operation

Let’s move forward and think about how we can check whether a number is a multiple of 3 or 5 without using the modulus operator. The first thing that we realize is that every number we get is made by adding 3 or 5 again and again. So we can simply use a Counter Variable to store the count of both 3 and 5 iterations. So whenever we reach a particular conditions (given in the below algorithm), we reset the counter variable to 0. This approach will help in solving the FizzBuzz Problem Statement.

  • Algorithm:
    • Initialise two variables to maintain count for fizz and buzz with 0.
    • We run a loop from 1 to n and increment the counter variables by 1.
    • Check if fizz counter is 3 and buzz count is  5, then print “FizzBuzz” and reset both the counters to 0.
    • Check if Fizz counter if 3 then print “Fizz” and reset the Fizz Counter to 0.
    • Check if Buzz Counter is 5 then print “Buzz” and reset the counter to 0.
    • If none of the above conditions are satisfied, then we can print the number.
  • Code
    Python
n = int(input())
fizz_count = 0
buzz_count = 0
for i in range(1, n+1):
    fizz_count += 1
    buzz_count += 1
    if fizz_count == 3 and buzz_count == 5:
        print("FizzBuzz")
        fizz_count = 0
        buzz_count = 0
    elif fizz_count == 3:
        print("Fizz")
        fizz_count = 0
    elif buzz_count == 5:
        print("Buzz")
        buzz_count = 0
    else:
        print(i)

Java

import java.util.*;

class Approach1 {

  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int fizz_count = 0;
    int buzz_count = 0;
    for (int i = 1; i <= n; ++i) {
      fizz_count++;
      buzz_count++;
      if (fizz_count == 3 && buzz_count == 5) {
        System.out.println("FizzBuzz");
        fizz_count = 0;
        buzz_count = 0;
      } 
      else if (fizz_count == 3) {
        System.out.println("Fizz");
        fizz_count = 0;
      } 
      else if (buzz_count == 5) {
        System.out.println("Buzz");
        buzz_count = 0;
      } 
      else 
        System.out.println(i);
    }
  }
}

C++

#include <iostream>
using namespace std;

int main(){
    int n;
    cin >> n;
    int fizz_count = 0;
    int buzz_count = 0;
    for (int i = 1; i < n + 1; i++){
        fizz_count += 1;
        buzz_count += 1;
        if (fizz_count == 3 and buzz_count == 5){
            cout << "FizzBuzz" << endl;
            fizz_count = 0;
            buzz_count = 0;
        }
        else if (fizz_count == 3){
            cout << "Fizz" << endl;
            fizz_count = 0;
        }
        else if (buzz_count == 5){
            cout << "Buzz" << endl;
            buzz_count = 0;
        }
        else
            cout << i << endl;
    }
    return 0;
}

Output:Input: N = 6 Output

1
2
Fizz
4
Buzz
Fizz
  • Time ComplexityIn the above approach without using modulus, we run only a single for loop and perform constant operations. The time complexity of the solution is O(n).
  • Space Complexity:In the above approach without using modulus, we do not use any extra space. Therefore, the total space complexity of the above logic is O(1).

Approach 3: Functional Approach – Using Map()

This approach uses the same logic as previous approaches, but the main key difference is its functional methodology and use of map functions. The map function is used to apply a particular function or a condition to all the items of an array or a list in Python. In this approach, we first create a function that would take an integer and modify its elements based on a function. The function will use the logic of String Concatenation to evaluate what will be the output of a given integer.

In C++, we use map_chr, and in Python, we use the map function to modify the list of elements.

  • Algorithm:
    • Create a list or array of 1 to n integers ( Both Inclusive).
    • Create a function that takes an integer as a parameter/input and returns the appropriate string or number as the output using the String Concatenation Approach.
    • Call that function using a map function, which will modify the elements of the list. 
    • Print the final output list.
  • Code

Python

def fizzbuzz(i):
    s = ""
    if i % 3 == 0:
        s += "Fizz"
    if i % 5 == 0:
        s += "Buzz"
    if len(s) == 0:
        s = str(i)
    return s


n = int(input())
ans = list(map(fizzbuzz, list(range(1, n + 1))))
for i in ans:
    print(i)

C++

#include <bits/stdc++.h>
using namespace std;

string fizzbuzz(int i){
    string s = "";
    if (i % 3 == 0)
        s += "Fizz";
    if (i % 5 == 0)
        s += "Buzz";
    if (s.size() == 0)
        s = to_string(i);
    return s;
}

int main()
{
    int n;
    cin >> n;
    vector<string> ans;
    for (int i = 1; i < n + 1; i++){
        string tmp = "";
        tmp = fizzbuzz(i);
        ans.push_back(tmp);
    }
    for (auto it : ans)
        cout << it << endl;
    return 0;
}

Java

import java.util.*;

class Approach6 {

  public static void main(String args[]) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    List<String> li = new ArrayList<>();
    for (int i = 1; i <= n; ++i) li.add(fizzbuzz(i));
    for (int i = 0; i < li.size(); ++i) System.out.println(li.get(i));
  }

  public static String fizzbuzz(int i) {
    String s = "";
    if (i % 3 == 0) s += "Fizz";
    if (i % 5 == 0) s += "Buzz";
    if (s.length() == 0) s = Integer.toString(i);
    return s;
  }
}

Output:

Input: N = 6 Output:

1
2
Fizz
4
Buzz
Fizz
  • Time ComplexityIn the above approach, we are using the Functional Approach with Map Technique, as we run only a single for loop and perform constant operations. The time complexity of the solution is O(N).
  • Space ComplexityIn the above approach, using the Functional Approach with Map Technique, we use an Extra Space. As a result, the total space complexity of the preceding logic is O(N).

Approach 4: Package Approach – Using FizzBuzzR

This approach is the easiest and simplest way to do FizzBuzz Solution in the R language. The R language has several user-friendly packages, one of which is FizzBuzzR. It has a lot of benefits, like faster execution, readability of code, and conciseness, as well as the disadvantage of limited options for optimization.

The FizzBuzz function in R takes five parameters in this case, i.e.

  • Start: The start of the range.
  • End: The End of the Range.
  • Step: Increase or decrease the count.
  • Mod1: Key for the first condition, i.e., “Fizz”.
  • Mod2: key for the second condition “Buzz”.
  • Algorithm:
    • Install the Package in the R Language, i.e., install.packages (“fizzbuzzR”)
    • Use the library(fizzbuzzR) module.
    • Finally, call the fizzbuzz function by passing the above parameters.
  • Code

R

Output:

Input: N = 6 Output

 1
    2
    Fizz
    4
    Buzz
    Fizz
  • Time ComplexityThis is the most optimal solution, as we don’t use any statements or any loops. The overall complexity of using the FizzBuzzR Package is O(1).
  • Space ComplexityThis approach, i.e., using the FizzBuzzR Package, is the most optimal; it doesn’t use any extra space. Therefore, its complexity is O(1).

Conclusion:

Let’s summarise our topic fizzbuzz program by discussing some of the main points.

  • The FizzBuzz Problem aids in the learning of fundamental programming concepts such as loops, strings, conditional statements (if-else-elif), operators (mathematical, logical, etc.), and various optimization techniques such as hashing.
  • The basic approach to solving the FizzBuzz problem utilizes modulus and if condition concepts, which are further improved by the String Concatenation Technique.
  • We can use the concept of hashmap to make the code more efficient toward an increase in the number of conditions.
  • We can use the map function to solve the fizz buzz problem by mapping all integers with a given function.
  • The R language provides us with case_when() and the FizzBuzzR library to solve the problem much faster and more conveniently.

Author