You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.9 KiB

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 that computes the value of pi 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 <stdio.h>
#include <stdint.h>

#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);
  }
}