blob: eedd76c43c0b391837ac8d662a77a64c39258b1a (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
/*
* Celebrate Pi day in C.
*
* See https://www.youtube.com/watch?v=RZBhSi_PwHU to watch Matt Parker
* do it the hard way.
*
* See https://www.youtube.com/watch?v=LFwSIdLSosI for a more in-depth
* explanation of why this works.
*/
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NR_PAIRS 1000000
static unsigned int
gcd(unsigned int a, unsigned int b)
{
unsigned int tmp;
while (b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return a;
}
static bool
coprimes(unsigned int a, unsigned int b)
{
return (gcd(a, b) == 1);
}
int
main(int argc, char **argv)
{
unsigned int i, total;
double pi;
srand(time(NULL));
for (i = 0, total = 0; i < NR_PAIRS; i++) {
if (coprimes(rand(), rand())) {
total++;
}
}
/* Division by zero ? What's the problem ? */
pi = sqrt(6. * NR_PAIRS / total);
printf("%f\n", pi);
}
|