Goal
Create a program/function that takes an input N, check if N random pairs of integers are relatively prime, and returns sqrt(6 * N / #coprime).
TL;DR
These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are eight more challenges to come. Checkout the sandbox post to make recommendations.
Simulation
What are we simulating? Well, the probability that two random integers are relatively prime (ie coprime or gcd==1) is 6/Pi/Pi, so a natural way to calculate Pi would be to scoop up two buckets (or handfuls) of rocks; count them; see if their gcd is 1; repeat. After doing this a (削除) couple (削除ここまで) lot of times, sqrt(6.0 * total / num_coprimes) will tend towards Pi. If calculating the square-root in post-apocalyptic world makes you nervous, don't worry! There is Newton's Method for that.
How are we simulating this?
- Take input
N
- Do the following
N times:
- Uniformly generate random positive integers,
i and j
- With
1 <= i , j <= 10^6
- If
gcd(i , j) == 1: result = 1
- Else:
result = 0
- Take the sum of the
N results, S
- Return
sqrt(6 * N / S)
enter image description here
Specification
- Input
- Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)
- Output
- Flexible, give output in any of the standard ways (eg return, print)
- White space, trailing and leading white space is acceptable
- Accuracy, please provide at least 4 decimal places of accuracy (ie
3.1416)
- Scoring
Test Cases
Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of N.
Input -> Output
----- ------
100 -> 3.????
10000 -> 3.1???
1000000 -> 3.14??
ḤRµȷ6Xµ€g2/ċ1÷³6÷½saves 2 bytes. (ȷ6is 10^6 in a single nilad,ċ1counts ones) \$\endgroup\$ȷ²is a tiny tiny bit faster thanȷ6) \$\endgroup\$ȷ²being two links doesn't hurt here, but would require an extra link or¤for some use cases \$\endgroup\$Ḥȷ6xX€should work for the random sampling. \$\endgroup\$