Skip to content

Instantly share code, notes, and snippets.

@jcdickinson
Created February 25, 2011 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcdickinson/843803 to your computer and use it in GitHub Desktop.
Save jcdickinson/843803 to your computer and use it in GitHub Desktop.
static void FizzBuzz(int number)
{
// 3 MOD 3 = 0. We actually want 1 for multiples of 3.
// So we store an incremented number so that we get 1
// for the binary operations. This applies to 5 as
// well.
// Valid numbers for X MOD 3 are { 0, 1, 2 }. Therefore
// we can simply AND it with 1. As such:
// { 0, 1, 2 } AND 1 =
// { 0, 1, 0 }
// Valid numbers for X MOD 5 are { 0, 1, 2, 3, 4 }. If we
// simply AND it with 1 we will get a false positive on 3.
// To avoid that we use MOD 3 to 'make' the 3 case 0.
// Unfortunately that will make the 4 case 1 as the
// sequence is now { 0, 1, 2, 0, 1 }. To avoid that we
// MOD it with 4 first. Finally we shift it left one bit
// to multiply it by 2. As such:
// { 0, 1, 2, 3, 4 } MOD 4 =
// { 0, 1, 2, 3, 0 } MOD 3 =
// { 0, 1, 2, 0, 0 } AND 1 =
// { 0, 1, 0, 0, 0 } SHL 1 =
// { 0, 2, 0, 0, 0 }
byte current = 0;
int inc = number + 1;
// 3 case.
current |= (byte)((inc % 3) & 1);
// 5 case.
current |= (byte)(((((inc % 5) % 4) % 3) & 1) << 1);
switch (current)
{
case 1:
Console.WriteLine("Fizz");
break;
case 2:
Console.WriteLine("Buzz");
break;
case 3: // 1 OR 2 = 3
Console.WriteLine("FizzBuzz");
break;
default:
Console.WriteLine(number);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment