Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@MawKKe
Last active June 29, 2019 22:41
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 MawKKe/ba323eee603150630547b9a15f4bdbae to your computer and use it in GitHub Desktop.
Save MawKKe/ba323eee603150630547b9a15f4bdbae to your computer and use it in GitHub Desktop.
Unconditional fizzbuzz
//
// Unconditional FizzBuzz
//
// Author: Markus (MawKKe) ekkwam@gmail.com | 2017-01-11
//
// Compile:
// gcc -std=c99 -Wall -Wextra -pedantic fizzbuzz.c -o fizzbuzz
//
#include <stdio.h>
#define LIM 30
// Divisible by 3 -> Fizz
// Divisible by 5 -> Buzz
// Divisible by both -> FizzBuzz
// Divisible by neither -> number
const char * msg[4] = {"%d\n", "Fizz\n", "Buzz\n", "FizzBuzz\n"};
void fizzbuzz(int n){
for(int i=1; i<=n; i++){
printf(msg[!(i%5) << 1 | !(i%3)], i);
}
}
int main(void){
fizzbuzz(LIM);
return 0;
}
// this solution creates a 2-bit value from the truth table of divisibilty.
// If
// A: Divisible by 5
// B: Divisible by 3
//
// Then
// A B | output
// ------------
// 0 0 | <number>
// 0 1 | Fizz
// 1 0 | Buzz
// 1 1 | FizzBuzz
//
// The 2-bit value can express integers 0..3 which can be used to index an array (msg).
//
// Rest is clever trickery with printf() - if there is no formatting specifiers in the string,
// then of course the value argument is ignored.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment