Created
June 7, 2022 12:43
-
-
Save AltimorTASDK/088d531c09badfaa47e2fb1a458432a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
static int abs(int n) | |
{ | |
const auto mask = n << 31; | |
return (n ^ mask) - mask; | |
} | |
static int odd_digit_sum_base4(int n) | |
{ | |
// Shift and add half the digits onto the other half with each pass | |
n = (n & 0x03030303) + ((n & 0x30303030) >> 4); | |
n = (n & 0x00FF00FF) + ((n & 0xFF00FF00) >> 8); | |
n = (n & 0x0000FFFF) + ((n & 0xFFFF0000) >> 16); | |
return n; | |
} | |
static void fizzbuzz(int n) | |
{ | |
// Divisibility by 3 for 0-48 | |
constexpr auto div3_mask = 0b1001001001001001001001001001001001001001001001001; | |
// Divisibility by 5 for 0-24 | |
constexpr auto div5_mask = 0b0000100001000010000100001; | |
const auto odd_sum = odd_digit_sum_base4(n); | |
const auto even_sum = odd_digit_sum_base4(n >> 2); | |
// Check digit sum divisibility for divisibility by base - 1 | |
const auto div3 = (div3_mask >> (odd_sum + even_sum)) & 1; | |
// Check alternating digit sum divisibility for divisibility by base + 1 | |
const auto div5 = (div5_mask >> abs(odd_sum - even_sum)) & 1; | |
printf((const char*[]) { | |
"%d\n", | |
"fizz\n", | |
"buzz\n", | |
"fizzbuzz\n" | |
}[div3 | (div5 << 1)], n); | |
} | |
int main() | |
{ | |
for (auto i = 1; i <= 100; i++) | |
fizzbuzz(i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment