Last active
January 31, 2021 15:05
-
-
Save BekzhanKassenov/e33fa8ca077d5648aefc1f8e55790e52 to your computer and use it in GitHub Desktop.
Solution for https://habr.com/ru/post/540136/
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 <stdio.h> | |
#include <string.h> | |
#define LIMIT 1000000000 | |
#define CHUNK_COUNT 35000 | |
#define CHUNK_NUMS 15 * CHUNK_COUNT | |
// max size of buffer for CHUNK_NUMS numbers (except 1B) | |
#define CHUNK_SIZE (119 * CHUNK_COUNT) | |
void print(); | |
char numbuf[13]; | |
char* num; | |
int numlen; | |
int main(void) { | |
// Keep trailing '\0' - useful for debug | |
numbuf[11] = '\n'; | |
numbuf[10] = '1'; | |
num = numbuf + 10; | |
// A digit and '\n' | |
numlen = 2; | |
int i; | |
for (i = 1; i < LIMIT - CHUNK_NUMS; i += CHUNK_NUMS) { | |
print(); | |
} | |
while (i <= LIMIT) { | |
if (0 == i % 3) { | |
if (0 == i % 5) { | |
printf("FizzBuzz\n"); | |
} else { | |
printf("Fizz\n"); | |
} | |
} else if (0 == i % 5) { | |
printf("Buzz\n"); | |
} else { | |
printf("%d\n", i); | |
} | |
i++; | |
} | |
return 0; | |
} | |
// 1 <= delta <= 3 | |
void inc(int delta) { | |
int carry = delta; | |
char *cur; | |
for (cur = numbuf + 10; cur >= num && carry; cur--) { | |
int add = *cur - '0' + carry; | |
carry = add >= 10; | |
*cur = add - 10 * carry + '0'; | |
} | |
*(num - 1) = '0' + carry; | |
num -= carry; | |
numlen += carry; | |
} | |
#define NUM do { memcpy(cur, num, numlen); cur += numlen; } while(0) | |
#define FIZZ do { memcpy(cur, "Fizz\n", 5); cur += 5; } while (0) | |
#define BUZZ do { memcpy(cur, "Buzz\n", 5); cur += 5; } while (0) | |
#define FIZZBUZZ do { memcpy(cur, "FizzBuzz\n", 9); cur += 9; } while (0) | |
void print() { | |
static char wrkbuf[CHUNK_SIZE]; | |
char *cur = wrkbuf; | |
int i; | |
for (i = 0; i < CHUNK_COUNT; i++) { | |
NUM; | |
inc(1); | |
NUM; | |
FIZZ; | |
inc(2); | |
NUM; | |
BUZZ; | |
FIZZ; | |
inc(3); | |
NUM; | |
inc(1); | |
NUM; | |
FIZZ; | |
BUZZ; | |
inc(3); | |
NUM; | |
FIZZ; | |
inc(2); | |
NUM; | |
inc(1); | |
NUM; | |
FIZZBUZZ; | |
inc(2); | |
} | |
fwrite(wrkbuf, cur - wrkbuf, 1, stdout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment