FizzBuzz program in javascript

We will implement a simple algorithm to solve the FizzBuzz problem in javascript.

FizzBuzz is the simple programming task which is asked to solve in many programming interviews.

Example

In this, we print all the numbers from 1 to N with a specific rule.
1) If the number is divisible by 3 then print ‘Fizz’.
2) If the number is divisible by 5 then print ‘Buzz’.
3) If the number is divisible by both 3 and 5 then print ‘FizzBuzz’.

Input:
10

Output:
1
2
'Fizz'
4
'Buzz'
'Fizz'
7
8
'Fizz'
'Buzz'

Implementation of FizzBuzz in javascript.

  • We will loop through all the numbers from 1 to N.
  • Then in each iteration we will first check if the number is divisible by both 3 and 5, then print ‘FizzBuzz’.
  • Else if it is divisible by only 3 then print ‘Fizz’ or If it is only divisible by 5 then print ‘Buzz’.
  • Otherwise just print the number.
  • Everything will be written in ES6.
let fizzBuzz = (n) => {
   for(let i = 1; i <= n; i++){
     if(i % 3 === 0 && i % 5 === 0){
        console.log('FizzBuzz');
     }else if(i % 3 === 0){
        console.log('Fizz');
     }else if(i % 5 === 0){
        console.log('Buzz');
     }else{
        console.log(i);
     }
   }
}
Input:
fizzBuzz(15);

Output:
1
2
"Fizz"
4
"Buzz"
"Fizz"
7
8
"Fizz"
"Buzz"
11
"Fizz"
13
14
"FizzBuzz"

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

Time and Space complexity

  • We are just iterating from 1 to N, so Time complexity is O(n).
  • We are using constant space, so Space complexity is O(1).

Leave a Reply

Your email address will not be published. Required fields are marked *