From 7797711ca923309277b05f9c7d82260792eee99c Mon Sep 17 00:00:00 2001 From: Miloslav Ciz Date: Fri, 31 Dec 2021 16:56:32 -0600 Subject: [PATCH] Update --- exercises.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 exercises.md diff --git a/exercises.md b/exercises.md new file mode 100644 index 0000000..13429a1 --- /dev/null +++ b/exercises.md @@ -0,0 +1,61 @@ +# Exercises + +Here let be listed exercises for the readers of this wiki. You can allow yourself to as many helpers and resources as you find challenging: with each problem you should either find out you know the solution or learn something new while solving it. + +1. SOMETHING EASY SHOULD BE HERE SO THAT NUBS ARENT DISCOURAGED BY FIRST QUESTION xD +2. Write a program in [C](c.md) that computes the value of [pi](pi.md) without using float/double and any libraries except for `stdio.h` and `stdint.h` -- you can only use built-in integer types and those from `stdint.h`. The program must compute pi as accurately as possible (at least 2 decimals) and write the value out as base 10 decimal. + +## Solutions + +A solution to each problem should be listed here -- keep in mind there may exist other solutions that those listed here. + +**solution 1**: +TODO + +**solution 2**: + +``` +#include +#include + +#define DECIMALS 10000 + +int main(void) +{ + int64_t previousError = 10000000000; + uint64_t previousPi = 0; + + for (uint64_t gridSize = 2; gridSize < 200000; gridSize *= 2) + { + /* We'll sample a grid of points and count those that fall inside the + circle with radius of gridSize. Thanks to the 8-symmtery of a circle we + only sample the 1/8th of the plane. */ + + uint64_t inCircle = 0; + + for (int y = 0; y < gridSize; ++y) + for (int x = y; x <= gridSize; ++x) + if ((x * x + y * y) / gridSize <= gridSize) // if distance is < radius + inCircle++; // count the point + + // compute pi from the formula for circle area (area = 2 * pi * r): + uint64_t pi = (inCircle * 8 * DECIMALS) / (gridSize * gridSize); + + int64_t error = pi - previousPi; + + if (error < 0) + error *= -1; + + if (error > previousError) // error got bigger due to overflows, stop + { + puts("that's it"); + break; + } + + previousError = error; + previousPi = pi; + + printf("%d.%d\n",pi / DECIMALS,pi % DECIMALS); + } +} +``` \ No newline at end of file