39
1
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
andj
- With
1 <= i , j <= 10^6
- If
gcd(i , j) == 1
:result = 1
- Else:
result = 0
- Uniformly generate random positive integers,
- Take the sum of the
N
results,S
- Return
sqrt(6 * N / S)
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
- Shortest code wins!
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??
1Does our answer need to work for
N = 1000000
or is it ok if the program returns e.g. a stack overflow ifN
is too big? – Fatalize – 2016-10-03T13:41:37.977@Fatalize if it is a limitation of the language, sure. Otherwise, you need to handle
N=10^6
. – NonlinearFruit – 2016-10-03T13:43:55.1931Related – Luis Mendo – 2016-10-03T14:01:10.180
2The goal is misleading, it states only one pair of integers is checked. – user253751 – 2016-10-04T02:08:04.763
@immibis I meant the goal to be a short overview with exact details in the specification. I thought the
#coprime
might indicate multiple pairs. – NonlinearFruit – 2016-10-04T04:23:30.6301Does the upper limit to the random numbers generated need to be exactly 1000000? Would a larger upper limit be acceptable? – Sok – 2016-10-04T12:24:25.783
@Sok A larger upper limit is acceptable – NonlinearFruit – 2016-10-04T13:15:30.023
I agree with @immibis, something like "check if
N
random pairs of integers are relatively prime" might be clearer. – 2012rcampion – 2016-10-05T04:16:48.053