This commit is contained in:
Miloslav Ciz 2024-10-01 13:26:35 +02:00
parent de9f98731e
commit aab4692f16
10 changed files with 1879 additions and 1801 deletions

View file

@ -156,4 +156,74 @@ int i;int main(){while(i<100){if(i++)P", ");int a=!(i%3)+!(i%5)*2;if(a)P"FizzBuz
It's almost definitely not minimal but can be a good start.
TODO: comun
And here is a completely different approach that's probably not so practical, at least not in most common situations, but may be worth discussing and could get you some style points in the discussion. It works on the principle of [sieve of Eratosthenes](sieve_of_eratosthenes.md), the advantage is it doesn't need ANY DIVISION at all, however it needs more memory (although we can fix this, see below). The idea is basically to first go from 0 to 100 by steps of 3 and mark all numbers we visit as divisible by 3, then do the same for 5, and then finally we go one by one and do the printing -- we know whether each number is divisible by the numbers we are interested in thank to the marks. Here is the base version:
```
#include <stdio.h>
#define NMAX 100
unsigned char divisibility[NMAX + 1];
int main(void)
{
for (int i = 0; i <= NMAX; i += 3) // mark all multiples of 3
divisibility[i] |= 0x01;
for (int i = 0; i <= NMAX; i += 5) // mark all multiples of 5
divisibility[i] |= 0x02;
for (int i = 1; i <= NMAX; ++i)
{
if (i > 1)
printf(", ");
if (divisibility[i])
printf("%s%s",
(divisibility[i] & 0x01) ? "Fizz" : "",
(divisibility[i] & 0x02) ? "Buzz" : "");
else
printf("%d",i);
}
return 0;
}
```
Now let's try to improve this -- we can in fact remove the requirement for the big array in which we mark number divisibility, we can just keep the next multiple of 3 and next multiple of 5 and simply increase them once we reach them. Here is what it could look like:
```
#include <stdio.h>
int main(void)
{
int next3Mult = 3, next5Mult = 5;
for (int i = 1; i <= 100; ++i)
{
int printNum = 1;
if (i > 1)
printf(", ");
if (i == next3Mult)
{
printf("Fizz");
next3Mult += 3;
printNum = 0;
}
if (i == next5Mult)
{
printf("Buzz");
next5Mult += 5;
printNum = 0;
}
if (printNum)
printf("%d",i);
}
return 0;
}
```