# Piecing Paired Primes

## Problem

You've stumbled upon a paradoxical mathematical phenomenon related to prime numbers. Consider the following scenario:

You have an infinite list of prime numbers: $$2, 3, 5, 7, 11, 13, 17, 19, ...$$

Now, you decide to pair up these prime numbers in a way that each prime is paired with its consecutive prime number and generate fractions by dividing the smaller number of each pair by the larger number. And you start adding them... $$\frac{2}{3}+\frac{3}{5}+\frac{5}{7}+\frac{7}{11}+\frac{11}{13}+\frac{13}{17}...$$ they seem to be converging!!!??? Your task is to calculate the sum of all fractions in this sequence.

Write a program or function that calculates the sum of these fractions up to a specified number of pairs (n).

## Input:

• An integer n representing the number of prime pairs to consider (1 ≤ n ≤ 1000).

## Output

• A floating-point number or The accurate fraction representing the sum of the fractions.

## Examples

$$n = 3$$ $$\frac{2}{3}+\frac{3}{5}+\frac{5}{7}=1.980952$$

Smallest code wins (bytes)

#### Some test cases

  3 =   1.980952  (208/105)
7 =   5.122912  (24845332/4849845)
9 =   6.742102  (21809669044/3234846615)
185 = 179.189745
564 = 556.886274
849 = 841.414962
999 = 991.228537

• The bit about converging seems confusingly worded because it sounds like the sum is converging, not the fractions themselves.
– xnor
Aug 22, 2023 at 5:15
• Things to avoid when writing challenges (including those that only apply to the previous version): real-valued outputs, prime numbers, non-observable requirements Aug 22, 2023 at 5:16
• @3.14 Honestly, golfs to generate prime numbers have gotten pretty stale on the site whether or not we use built-ins.
– xnor
Aug 22, 2023 at 5:17
• @3.14 I don't know that theorem, but the sum of reciprocals of primes diverges. Aug 22, 2023 at 5:44
• I'm completely sure what requiring "A floating-point number" actually means, but I suspect that this is intended to forbid outputting as a rational number expressed as a fraction. This is Husk's (and other languages') default rational output, and is normally allowed by default. Converting this representation to decimal with a decimal point would require a lot of code unrelated to the main problem. So downvoting. Aug 22, 2023 at 7:06

# Python 3, 66 bytes

f=lambda n,p=3,P=4,d=2:n and P%p*d/p+f(n-P%p,p+1,P*p*p,[d,p][P%p])


Try it online!

The Wilson's Theorem generator strikes again. Similar to the template for the first n primes here, but also stores the previous prime as d and keeps the running sum of the ratios.

# Desmos, 69 bytes

L=[2...7920]
P=L[∏_{d=3}^Lmod(L,d-1)>0]
f(k)=∑_{n=1}^kP[n]/P[n+1]


Try It On Desmos!

Try It On Desmos! - Prettified

Probably golfable but this is the best I could think of for now.

# Pari/GP, 48 38 bytes

Saved 10 bytes thanks to the comment of @alephalpha

f(n)=sum(k=1,n,prime(k)/prime(k+1))*1.


Try it online!

• f(n)=sum(k=1,n,prime(k)/prime(k+1)), or f(n)=sum(k=1,n,prime(k)/prime(k+1))*1. if you want to output a floating-point number. Aug 23, 2023 at 8:49

# Husk, 8 7 bytes

Σ↑Ẋ/İp


Try it online!

Σ↑Ẋ/İp
Ẋ      # map over adjacent pairs of values
/    #   flipped division: x ÷ y
İp  # apply this to the infinite list of primes
↑       # then take the first arg1 values
Σ        # and sum them


# Factor + math.primes math.unicode, 35 bytes

[ 1 + nprimes 2 clump unzip v/ Σ ]


Try it online!

         ! 3
1        ! 3 1
+        ! 4
nprimes  ! { 2 3 5 7 }
2        ! { 2 3 5 7 } 2
clump    ! { { 2 3 } { 3 5 } { 5 7 } }
unzip    ! { 2 3 5 } { 3 5 7 }
v/       ! { 2/3 3/5 5/7 }
Σ        ! 1+103/105


# Ruby -rprime, 42+6 = 48 bytes

->n{k=0;Prime.take(n+1).sum{|x|k*1.0/k=x}}


Try it online!

• You could save a single byte by changing 1.0 to 1r. Aug 22, 2023 at 12:56
• And another two with Ruby 2.7 Numbered Parameters, .sum{k*1r/k=_1} Attempt This Online Aug 22, 2023 at 23:02

# 05AB1E, 6 5 bytes

ÝØü/O


Explanation:

Ý      # Push a list in the range [0, (implicit) input]
Ø     # Convert each to their 0-based n'th prime
ü    # For each overlapping pair of values:
/   #  Divide them
O  # Them sum all these decimal values together
# (which is output implicitly as result)


# Python 3, 131 112 bytes

-19 thanks to bsoelch

lambda n:sum(x[k]/x[k+1]for k in range(n))
x=[i for i in range(2,7920)if not[i%j for j in range(2,i)if not i%j]]


Try it online!

Old explanation:

lambda n:                                # lambda with an argument
x:=[i for i in range(2,7920)if not[i%j for j in range(2,i)if not i%j]][:n+1]
# prime getter till 1000. 7919 is 1000th prime, slice until n+1
sum(x[k]/x[k+1]for k in range(len(x)-1)) # sum it up
[1]                                      # and return the latter

• You can pre-compute the array 112 bytes Aug 22, 2023 at 6:01

# Raku, 41 bytes

[\+] {.(2)Z/.(3)}({grep &is-prime,$_..*})  Try it online! This is an expression for the infinite sequence of partial sums. • { grep &is-prime,$_ .. * } is an anonymous function that returns a sequence of primes starting from the number given as its argument.
• { .(2) Z/ .(3) } is another anonymous function that is given the previous anonymous function as its argument in the variable $_, and evaluated immediately. .(2) calls the first function with the number 2, generating the primes starting from 2, and likewise with .(3). Z/ zips those sequences together with division, producing the sequence of fractions. • [\+] produces the infinite sequence of partial sums. # Python, 71 bytes lambda n:sum(p(k+1)/p(k+2)for k in range(n)) from sympy import* p=prime  Attempt This Online! ## Explanation prime computes the n-th prime # Python, 105 bytes longer but faster lambda n:sum(a/b for(a,b)in i.pairwise(i.islice(sympy.primerange(4**n),n+1))) import sympy,itertools as i  Attempt This Online! ## Explanation Uses the fact that the n+1-st prime is less than 4n+1 to obtain a list of the first n+1 primes from the list of the primes less than n (sympy.primerange). pairwise groups the elements in adjacent pairs # Thunno 2+, 7 bytes ÆpDḣỊØ.  Try it online! 2 flags -> 1 flag thanks to Neil #### Explanation ÆpDḣỊØ. # Implicit input Æp # First (input + 1) primes Dḣ # Push a copy without the first item Ị # Reciprocal of each Ø. # Dot product of the two lists # Implicit output  • 8 bytes flagless: ⁺ÆpDḣỊØ. – Neil Aug 22, 2023 at 8:28 • @Neil or 7 bytes with 1 flag... Thanks! Aug 22, 2023 at 8:50 # Vyxals, 35 bitsv2, 4.375 bytes ʀǎ¨p/  Try it Online! Works for any n >= 1 (even bigger than 1000). The flag is for display purposes. ## Explained ʀǎ¨p/­⁡​‎‎⁪⁡⁪⁠⁪⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁪‏‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁪‏‏​⁡⁠⁡‌⁣​‎‏​⁢⁠⁡‌­ ʀǎ # ‎⁡First n prime numbers ¨p/ # ‎⁢With every overlapping pair reduced by divison # ‎⁣Automatically sum 💎  Created with the help of Luminespire. # sclin, 20 bytes $P"1dp"Q / rev tk +/


Try it here!

For testing purposes:

999 ; 20N>d
$P"1dp"Q / rev tk +/  NOTE: the default representation is a rational number, but 20N>d converts the representation to decimal for convenience. ## Explanation Prettified code: $P 1.dp Q / rev tk +/


Assuming input n:

• $P infinite list of primes • 1.dp Q duplicate and drop first item • / element-wise divide • rev tk +/ take n elements and sum # Excel, 127 bytes =LET( a,ROW(1:7327), b,FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2), SUM(EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}))) )  Input in cell A1. Fails for A1>932. Explanation ROW(1:7327) # Vertical array of integers 1 to 7327 TOROW(a) # Transpose the above MOD(a,TOROW(a)) # 2D array of all those integers modulo all those integers MOD(a,TOROW(a))=0) # Which of these is equal to 0 N(MOD(a,TOROW(a))=0) # Convert Booleans to ones and zeroes a^0 # Vertical array of size 7327, each entry unity MMULT(N(MOD(a,TOROW(a))=0),a^0) # Matrix multiplication of the above arrays MMULT(N(MOD(a,TOROW(a))=0),a^0)=2 # Which of these is equal to 2, i.e. only divisors are unity and itself FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2) # Filter array of integers accordingly, i.e. list of primes <=7327 SEQUENCE(A1) # Vertical array from 1 to value in cell A1 SEQUENCE(A1)+{0,1} # Additional column added to above with values offset by 1 INDEX(b,SEQUENCE(A1)+{0,1}) # Index list of primes with these indices INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1} # Reciprocate the last entry in each pair with unity LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}) # Take the natural logarithm MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}) # Matrix multiplication for pairwise summation EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1})) # Take the natural exponentiation SUM(EXP(MMULT(LN(INDEX(b,SEQUENCE(A1)+{0,1})^{1,-1}),{1;1}))) # Sum all entries  # Charcoal, 32 bytes Ｎθ→→Ｗ¬›Ｌυθ¿⬤υ﹪ⅈκ⊞υⅈＭ→ＩΣＥΦυκ∕§υκι  Try it online! Link is to verbose version of code. Explanation: Ｎθ→→Ｗ¬›Ｌυθ¿⬤υ﹪ⅈκ⊞υⅈＭ→  Input n and generate the first n+1 primes using the same method as for my answer to Number of bits needed to represent the product of the first primes. ＩΣＥΦυκ∕§υκι  Divide each prime by its successor and output the sum. 30 bytes using the newer version of Charcoal on ATO: Ｎθ→→Ｗ¬›Ｌυθ¿⬤υ﹪ⅈκ⊞υⅈＭ→ＩΣ×υ∕¹Φυκ  Attempt This Online! Link is to verbose version of code. Explanation: Takes the dot product of the primes with the reciprocals of the odd primes. # JavaScript (ES6), 56 bytes n=>(g=(p,d=k++)=>k%d--?g(p,d):d?g(p):n--&&p/k+g(k))(k=2)  Try it online! # Wolfram Language (Mathematica), 43 32 bytes Saved 11 bytes thanks to the comment of @Roman N@Sum[Prime@i/Prime[i+1],{i,#}]&  Try it online! • 32 bytes Aug 24, 2023 at 8:51 # GAWK, 49 47 bytes func f(n){t=0;for(i=1;i<=n;)t+=$i/$++i;print t}  Try it online! • -2 bytes, thanks to @ceilingcat : $(++i) to $++i This one implies that the input file is an infinite list of prime number. The function is still taking an integer n as argument. As mentionned by @Olivier Dulac, this script need to run using gawk or other awk variant that support having multiple digits fields. He also suggested a variant that could work with Unix Shell, that would be 61 bytes, and would take as input file an infinite list of prime number, with one number per record : # HEADER BEGIN{OFMT = "%.6f"} # Get precision set up #HEADER {a[NR]=$0}func f(n){t=0;for(i=1;i<=n;)t+=a[i]/a[++i];print t}

# FOOTER
END{
f(3)
f(185)
f(564)
f(849)
f(999)
}
# FOOTER


# AWK, 120 111 109 bytes

{for(a[n=1]=2;t=j=n<1e3;a[++n]=m)for(m=a[n]+(i=1);++i<m;)i=m%i<1?2+0*m++:i;for(;j<$0;)t+=a[++j]/a[1+j];$1=t}1


Try it online!

• -9 bytes, thanks to @ceilingcat
• -2 bytes, replaced print t with $1=t, then 1 as precision is not necessary This one work with just n as input. It only supplies 999 pair of prime number, but if you change 1e3 with 1e4 it will supplies 9999, it will just get 10 time longer for each lines. • It looks like you're taking the primes themselves as input, but input should be "An integer n representing the number of prime pairs to consider (1 ≤ n ≤ 1000)." Aug 22, 2023 at 16:13 • @Jonah in the first example, yes and no. In the sense that yes the input file is the primes themselves, and no in the sense that the function is taking an integer n representing the number of prime pairs. I couldn't find anything clear in the meta post about that... Anyway, that is also why I added the second line as I wasn't sure about those rule. Aug 22, 2023 at 22:14 • just a nitpick: for your first program:$n are limited in scope (especially if using regular (and old) awk, and not gawk). a variant could read input one per line with a line : {a[NR]=\$0}, and your function could then use a[i]/a[++i] ? Aug 23, 2023 at 9:57
• @OlivierDulac you're right, I added explanation based on your comment, and changed awk to gawk for that answer Aug 23, 2023 at 11:54

# Japt v2.0a0 -x, 9 bytes

_j}jUÄ ä÷


Try it

# Pyt, 7 bytes

⁺řᵽᵮʁ/Ʃ


Try it online!

⁺              implicit input; increment
ř             řangify (1...n+1)
ᵽ            get the kth ᵽrime number
ᵮ           convert to ᵮloat
ʁ/         ʁeduce the array by division (each element divided by the next)
Ʃ        Ʃum; implicit print
`