Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <limits.h>
- #include <stdio.h>
- #include <stdlib.h>
- // 0 or 1
- unsigned is_divisible(unsigned x, unsigned d) {
- unsigned rem = x % d;
- rem--;
- return ((rem & (1 << sizeof(rem) * CHAR_BIT - 1)) >>
- (sizeof(rem) * CHAR_BIT - 1));
- }
- typedef void (*do_num_f)(unsigned i);
- void do_last(unsigned i) {
- (void)(i);
- printf("Good bye!\n");
- exit(0);
- }
- void do_3_and_5(unsigned i) {
- (void)(i);
- printf("FizzBuzz!\n");
- }
- void do_3(unsigned i) {
- (void)(i);
- printf("Fizz!\n");
- }
- void do_5(unsigned i) {
- (void)(i);
- printf("Buzz!\n");
- }
- void do_other(unsigned i) { printf("%u\n", i); }
- do_num_f do_num[5] = {do_other, do_3, do_5, do_3_and_5, do_last};
- // 0 - others
- // 1 - 3
- // 2 - 5
- // 3 - 15
- // 4 - last
- unsigned get_do_index(unsigned i, unsigned last) {
- unsigned is_divisible_last = is_divisible(i, last);
- unsigned is_divisible_5 = is_divisible(i, 5);
- unsigned is_divisible_3 = is_divisible(i, 3);
- return is_divisible_last * 4 +
- (is_divisible_5 * 2 + is_divisible_3 * 1) * (is_divisible_last ^ 1);
- }
- int main(int argc, char *argv[]) {
- printf("Branchless FizzBuzz!\n");
- for (unsigned i = 1;; i++)
- do_num[get_do_index(i, 101)](i);
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement