A curious prime fraction formula
Mathematica, 32 bytes
1##&@@(1-2/(Prime@Range@#^2+1))&
An unnamed function that takes integer input and returns the actual fraction.
This uses the fact that (p2-1)/(p2+1) = 1-2/(p2+1)
. The code is then golfed thanks to the fact that Mathematica threads all basic arithmetic over lists. So we first create a list {1, 2, ..., n}
, then retrieve all those primes and plug that list into the above expression. This gives us a list of all the factors. Finally, we multiply everything together by applying Times
to the list, which can be golfed to 1##&
.
Alternatively, we can use Array
for the same byte count:
1##&@@(1-2/(Prime~Array~#^2+1))&
M, 9 bytes
RÆN²‘İḤCP
Try it online!
Trivia
Meet M!
M is a fork of Jelly, aimed at mathematical challenges. The core difference between Jelly and M is that M uses infinite precision for all internal calculations, representing results symbolically. Once M is more mature, Jelly will gradually become more multi-purpose and less math-oriented.
M is very much work in progress (full of bugs, and not really that different from Jelly right now), but it works like a charm for this challenge and I just couldn't resist.
How it works
RÆN²‘İḤCP Main link. Argument: n
R Range; yield [1, ..., n].
ÆN Compute the kth primes for each k in that range.
²‘ Square and increment each prime p.
İ Invert; turn p² + 1 into the fraction 1 / (p² + 1).
Ḥ Double; yield 2 / (p² + 1).
C Complement; yield 1 - 2 / (p² + 1).
P Product; multiply all generated differences.
Python 2, 106 bytes
from fractions import*
n=input()
F=k=P=1
while n:b=P%k>0;n-=b;F*=1-Fraction(2*b,k*k+1);P*=k*k;k+=1
print F
The first and fourth lines hurt so much... it just turned out that using Fraction
was better than multiplying separately and using gcd
, even in Python 3.5+ where gcd
resides in math
.
Prime generation adapted from @xnor's answer here, which uses Wilson's theorem.