Starting up...

FizzBuzz without multiplication or division

This is the first of a three-part series: Part 2, Part 3.

 

I use FizzBuzz as a warm-up question on interviews, so I have had time to ponder it quite a bit. As a thought experiment, I wondered if I could come up with an implementation that does not depend on run-time multiplication (or its inverse, division). I decided a very readable approach would be to use a circular look-up table.

void FizzBuzz(int n) {
  int rg[15] = { 15, 0, 0, 3, 0, 5, 3, 0, 0, 3, 5, 0, 3, 0, 0 };
  int ix = 1;
  
  for(int i=1; i<=n; i++)
  {
     if(rg[ix] == 0) printf("%d\n", i);
     else if(rg[ix] == 3) printf("Fizz\n");
     else if(rg[ix] == 5) printf("Buzz\n");
     else if(rg[ix] == 15) printf("FizzBuzz\n");
     
     ix++;
     if(ix==15) ix = 0;
  }
}

There is a part of my brain that clings to the idea that the ALU is always the bottleneck. Though I know this isn't true, it's still nice to experiment with constraining myself on simple problems such as FizzBuzz, especially when I can find an elegant solution underneath.

GitHub Stack Overflow LinkedIn YouTube