This commit is contained in:
Miloslav Ciz 2024-06-28 13:51:48 +02:00
parent 03375916d0
commit 681319f2f2
24 changed files with 1903 additions and 1889 deletions

View file

@ -44,9 +44,9 @@ int main(void)
}
```
It [works](just_werks.md), however with a number of issues. Firstly we see that for every number we check we potentially test the divisibility by 3 and 5 twice, which is not [good](good.md), considering division (and modulo) are one of the slowest instructions. We also reuse the magic constants 3 and 5 in different places, which would start to create a huge mess if we were dealing with many more divisors. There is also a lot of branching, in the main divisibility check we may jump up to three times for the checked number -- jump instruction are slow and we'd like to avoid them (again, consider we were checking e.g. divisibility by 1000 different numbers).
It [works](just_werks.md), however with a number of issues. Firstly we see that for every number we check we potentially test the divisibility by 3 and 5 twice, which is not [good](good.md), considering division (and modulo) are one of the slowest instructions. We also reuse the magic constants 3 and 5 in different places, which would start to create a huge mess if we were dealing with many more divisors. There is also a lot of branching, in the main divisibility check we may jump up to three times for the checked number -- jump instruction are slow and we'd like to avoid them (again, consider we were checking e.g. divisibility by 1000 different numbers). A first, tiny optimization (that here will likely be performed automatically) to notice is that `i % 3 == 0 && i % 5 == 0` can be changed to just `i % 15 == 0`.
When asked to optimize the algorithm a bit one might come up with something like this:
When asked to optimize the algorithm a bit more one might come up with something like this:
```
#include <stdio.h>