Was reading about FizzBuzz/Algo again and I guess the modulo run-time.

The most optimal solution I came across is like:

if (x % 15) FizzBuzz
else if (x % 3) Buzz
else if (x % 5) Fizz
else x

But then how long does % take? Should you care?

I was thinking it should use variables:

var f = x % 3 == 0
var b = x % 5 == 0

if (f && b) FizzBuzz
else if (f) Fizz
else if (b) Buzz
else x

  • 6
    But then I guess either is still O(N)? So when do you stop caring?
  • 2
    In MIPS architecture it's two pseudoinstructions: one for the division and another to get the remainder.
    The former takes about three or four instructions, the latter it's just a mov.

    Don't know about Intel and/or AMD, but I think it might be similar...
  • 3
    This is certainly not the fastest or most efficient way but it's one of the easiest to add conditions to.
  • 2
    @billgates Fizz and Buzz are in the object on lines 1-4. The rest of the code loops from 0 to 100, then for every loop, looping through the object and checking if i % Number(key) = 0. So adding another condition like mod 7, would be easy. Just add '7': 'Bazz' to the object.
  • 0
    @olback yes took me a while to read that the function was printing for each and Number I guess is done internal int to string function
  • 2
    @olback That's JavaScript... obviously it is not the fastest ^^
  • 3
    def fizzbuzz(count=100)
    1.upto(count) do |number|
    line = ""
    line += "fizz" if number%3 == 0
    line += "buzz" if number%5 == 0
    printf(line + "\n")

  • 1
    The whole point of doing run time analysis is that you do not have to worry about how much time an instruction takes to execute. Same instruction on a very old hardware might take more time than a newer one but the run time remains same if you are using asymptotic notations ( which you are) 😉
  • 1
    @billgates it will always be O(N) no matter what trick you use. Because To print fizz bizz you have to check all elements at least once so for the input size N the run time will always be O(N). I suggest you read a little on run time analysis , it will give you a more clear idea on why such optimisations are useless
  • 1
Add Comment