[your code here]
Paul Backus
snarwin at gmail.com
Tue Apr 27 21:43:06 UTC 2021
On Tuesday, 27 April 2021 at 21:04:19 UTC, Jeff Pratt wrote:
> ```
> // Estimate π using random integers
> void main()
> {
> import std.stdio, std.random, std.math, std.conv;
> ulong gcd(ulong a, ulong b)
> {
> if (b == 0) return a;
> return gcd(b, a % b);
> }
> Mt19937_64 gen; gen.seed(unpredictableSeed!ulong);
> int pairCount = 1_000_000;
> int coprimeCount = 0;
> ulong a, b;
> for (int i = 0; i < pairCount; i++) {
> a = gen.front; gen.popFront();
> b = gen.front; gen.popFront();
> if (gcd(a, b) == 1) coprimeCount++;
> }
> double prob = coprimeCount.to!double / pairCount.to!double;
> writefln("π ≈ %.15f", sqrt(6.0 / prob));
> }
> ```
Nice example! A couple small improvements:
* You can use `std.numeric.gcd` instead of writing your own.
* You can use a `foreach` loop instead of a `for` loop.
```
// Estimate π using random integers
void main()
{
import std.stdio, std.random, std.math, std.conv, std.numeric;
Mt19937_64 gen; gen.seed(unpredictableSeed!ulong);
int pairCount = 1_000_000;
int coprimeCount = 0;
ulong a, b;
foreach (int i; 0 .. pairCount) {
a = gen.front; gen.popFront();
b = gen.front; gen.popFront();
if (gcd(a, b) == 1) coprimeCount++;
}
double prob = coprimeCount.to!double / pairCount.to!double;
writefln("π ≈ %.15f", sqrt(6.0 / prob));
}
```
More information about the Digitalmars-d
mailing list