GolfScript, 59 characters
~:N..*.,2>{:P{(.P\%}do(!},{{N-.*}$0=}:C~[1.{.@+.N<}do]C+++4/
This script does not fulfill some of the requirements:
- It only works correctly for inputs
n >= 2
, otherwise it crashes.
- The output is truncated to an integer.
- Terrible performance for any moderately large
n
A brief walkthrough of the code:
~:N..*
The input is stored in N, and we push both n
and the square n*n
right away.
.,2>
We will generate a list of primes by filtering the array [2..n*n]
. We use our previous calculation of n*n
as a (very bad!) upper bound for finding a prime that is larger than n.
{:P{(.P\%}do(!},
Our previous array is filtered by trial division. Each integer P is tested against every integer [P-1..1].
{{N-.*}$0=}:C~
Sorts the previous array based on the distance to n
, and grabs the first element. Now we have the closest prime.
[1.{.@+.N<}do]C
We generate Fibonnacis until we get one greater than n
. Fortunately, this algorithm naturally keeps track of the previous Fibonnaci, so we throw them both in an array and use our earlier distance sort. Now we have the closest Fibonnaci.
+++4/
Average. Note that GolfScript doesn't have support for floats, so the result is truncated.
GolfScript, 81 characters
Here is a variant that fulfills all of the requirements.
~:N..*2N*,3,|2,^{:P{(.P\%}do(!},{{N-.*}$0=}:C~[0.1{.@+.N<}do]C+++100:E*4/.E/'.'@E%
To ensure proper behavior for n<2
, I avoid 2<
(crashes when the array is small), and instead use 3,|2,^
. This makes sure the prime candidate array is just [2]
when n < 2
. I changed the upper bound for the next prime from n*n
to 2*n
(Bertrand's postulate). Also, 0 is considered a Fibonnaci number. The result is calculated in fixed point math at the end. Interestingly, it seems like the result is always in fourths (0, .25, .5, .75), so I hope 2 decimal places of precision is sufficient.
My first crack at using GolfScript, I'm sure there is room for improvement!