8
\$\begingroup\$

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
\$\endgroup\$
11
  • 9
    \$\begingroup\$ The bit about converging seems confusingly worded because it sounds like the sum is converging, not the fractions themselves. \$\endgroup\$
    – xnor
    Aug 22, 2023 at 5:15
  • 2
    \$\begingroup\$ Things to avoid when writing challenges (including those that only apply to the previous version): real-valued outputs, prime numbers, non-observable requirements \$\endgroup\$
    – Bubbler
    Aug 22, 2023 at 5:16
  • 2
    \$\begingroup\$ @3.14 Honestly, golfs to generate prime numbers have gotten pretty stale on the site whether or not we use built-ins. \$\endgroup\$
    – xnor
    Aug 22, 2023 at 5:17
  • 7
    \$\begingroup\$ @3.14 I don't know that theorem, but the sum of reciprocals of primes diverges. \$\endgroup\$
    – alephalpha
    Aug 22, 2023 at 5:44
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Aug 22, 2023 at 7:06

19 Answers 19

9
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – alephalpha
    Aug 23, 2023 at 8:49
5
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Ruby -rprime, 42+6 = 48 bytes

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

Try it online!

\$\endgroup\$
2
3
\$\begingroup\$

05AB1E, 6 5 bytes

ÝØü/O

Try it online or verify all test cases.

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)
\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You can pre-compute the array 112 bytes \$\endgroup\$
    – bsoelch
    Aug 22, 2023 at 6:01
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ 8 bytes flagless: ⁺ÆpDḣỊØ. \$\endgroup\$
    – Neil
    Aug 22, 2023 at 8:28
  • \$\begingroup\$ @Neil or 7 bytes with 1 flag... Thanks! \$\endgroup\$
    – The Thonnu
    Aug 22, 2023 at 8:50
3
\$\begingroup\$

Vyxal s, 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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 32 bytes

Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IΣEΦυκ∕§υκι

Try it online! Link is to verbose version of code. Explanation:

Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→

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.

IΣEΦυκ∕§υκι

Divide each prime by its successor and output the sum.

30 bytes using the newer version of Charcoal on ATO:

Nθ→→W¬›Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IΣ×υ∕¹Φυκ

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.

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 32 bytes \$\endgroup\$
    – Roman
    Aug 24, 2023 at 8:51
2
\$\begingroup\$

GAWK, 49 47 bytes

func f(n){t=0;for(i=1;i<=n;)t+=$i/$++i;print t}

Try it online!

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.

\$\endgroup\$
4
  • \$\begingroup\$ 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)." \$\endgroup\$
    – Jonah
    Aug 22, 2023 at 16:13
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Aug 22, 2023 at 22:14
  • 1
    \$\begingroup\$ 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] ? \$\endgroup\$ Aug 23, 2023 at 9:57
  • 1
    \$\begingroup\$ @OlivierDulac you're right, I added explanation based on your comment, and changed awk to gawk for that answer \$\endgroup\$ Aug 23, 2023 at 11:54
1
\$\begingroup\$

Japt v2.0a0 -x, 9 bytes

_j}jUÄ ä÷

Try it

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.