# Distance to the average of the next two prime numbers

Suppose we have a sequence $$\P\$$. Every element $$\P_n\$$ represents the distance between the $$\n^{th}\$$ prime number and the average of the next two prime numbers.

For example, $$\P_1\$$ would be the distance between the first prime number (2) and the average of the next two prime numbers (3 and 5), so $$\P_1 = \frac{3+5}{2} - 2 = 2\$$. Similarly, $$\P_2 = \frac{5+7}{2} - 3 = 3\$$.

## Input

Your input is an integer $$\n\$$. You may assume $$\n>0\$$.

## Output

Your task is to print out the sequence $$\P\$$ up to $$\n\$$, starting from $$\P_1\$$. You can format your output however you like as long as every element is clearly separated.

## Rules

• This is , so shortest number of bytes wins.
• You can assume that every computed number will be within the limits of the language you choose, so no need to worry about how big $$\n\$$ or $$\P_n\$$ can get.

## Test cases

Input            Output
n = 1            2
n = 2            2, 3
n = 5            2, 3, 4, 5, 4
n = 10           2, 3, 4, 5, 4, 5, 4, 7, 7, 5


(If you're curious, this sequence is A305748!)

• Welcome to Code Golf! I'd recommend using the standard sequence rules (which can be found in the tag wiki/"learn more..."), which allow a few other output formats, like an infinite iterator or just the Nth term. Other than that, this looks like a great question! Feb 6, 2023 at 14:14

# Vyxal, 8 bytes

-1 byte thanks to AndrovT

ƛ⇧ṡ‹ǎḣṁε


Explantion:

ƛ⇧ṡ‹ǎḣṁε
ƛ           Implicitly take input, convert it to a range and open mapping lambda :P
⇧ṡ         Range between n and n+2
‹ǎ       Decrement and get the respective prime (1-indexed)
ḣṁε    Head extract; push mean and get the abs difference

• 9 as an infinite list Feb 6, 2023 at 18:58
• 8 (7 to output nth number (6 0-indexed)) Feb 6, 2023 at 19:43
• @AndrovT how do you always manage to golf every single answer of mine Feb 6, 2023 at 21:18

# JavaScript (ES6), 76 bytes

Returns a space-separated string.

f=(n,q=p=3,r=2,x=p++)=>n?--x?f(n,q,r,p%~x?x:p++):(p+q)/2-r+' '+f(n-1,p,q):''


Try it online!

### Commented

f = (               // f is a recursive function taking:
n,                //   n = number of terms to generate
q =               //   q = previous confirmed prime
p = 3,            //   p = current prime candidate
r = 2,            //   r = penultimate confirmed prime
x = p++           //   x = divisor (post-increment p here)
) =>                //
n ?                 // if we still have some terms to generate:
--x ?             //   decrement x; it it's not zero:
f(              //     do a recursive call:
n, q, r,      //       pass n, q and r unchanged
p % ~x ?      //       if x + 1 does not divide p:
x           //         keep using x as the divisor
:             //       else (p is composite):
p++         //         reset the divisor to p and increment p
)               //     end of recursive call
:                 //   else (p is prime):
(p + q) / 2 - r //     append (p + q) / 2 - r, which is the next
+               //     term of the sequence by definition
' ' +           //     followed by a space
f(              //     followed by the result of a recursive call:
n - 1,        //       decrement n
p, q          //       set (q, r) = (p, q)
)               //     end of recursive call
:                   // else:
''                //   stop


# 05AB1E, 10 bytes

ÌÅpü3ε+;α


Or alternatively:

>ÝØDü2ÅA¦α


Explanation:

Ì           # Increase the (implicit) input-integer by 2
Åp         # Pop and push the first input+2 amount of prime numbers
ü3       # Get all overlapping triplets of this list
ε      # Map each triplet to:
#  Pop and push the three values in the triplet separated to the stack
+    #  Add the top two together
;   #  Halve this sum
α  #  Get the absolute difference with the third one
# (after which the list is output implicitly as result)

>           # Increase the (implicit) input-integer by 1
Ý          # Pop and push a list in the range [0,input+1]
Ø         # Get the 0-based index for each of these values
D        # Duplicate this list
ü2      # Get all overlapping pairs of the copy
ÅA    # Get the arithmetic mean of each inner pair
¦   # Remove the first one
α  # Get the absolute difference between the values in the two lists
# (after which the list is output implicitly as result)


# Husk, 10 bytes

↑Ẋ₁İp
≠⁰½+


Try it online!

≠⁰½+    # helper function with 3 args:
≠       # absolute difference between
⁰      #   first arg and
½     #   half
+    #   the sum of
#   the (implicit) other 2 args

↑Ẋ₁İp   # main program:
↑       # get the first input elements of
Ẋ₁     #   applying helper function ₁ to groups of 3
İp   #   from the infinite list of primes


Same byte-count to output the n-th element (by swapping the initial ↑ for ! [index]), or one byte less to output the infinite sequence (9 bytes, by omitting the initial ↑).

# Factor + grouping.extras math.primes, 46 bytes

[ 2 + nprimes [ + 2/ - abs ] 3 clump-map ... ]


Could be 42 bytes without the restrictive IO.

2 + nprimes       ! get the first input+2 primes
[                 ! begin clump-map
+ 2/          ! the average of the next two primes
- abs         ! subtracted by the current prime
] 3 clump-map     ! map over every three elements with overlapping
...               ! prettyprint a sequence of any length to stdout


# Java 8, 111 106 bytes

n->{for(int a=2,b=3,c,k=5;n>0;){for(c=1;k%++c>0;);if(k++==c){System.out.println((b+c)/2-a);a=b;b=c;n--;}}}


Prints the results on separated newlines to STDOUT.

Try it online.

Explanation:

n->{              // Method with integer parameter and no return-type
int a=2,b=3,    //  Previous two primes, starting at hard-coded 2 and 3
c,          //  Current prime, uninitialized
k=5;        //  Prime-loop integer, starting at the third prime 5
for(;n>0;){     //  Loop as long as the input n is not 0 yet:
for(c=1;      //   Reset c to 1
k%++c>0;);//   Keep increasing c as long as c is NOT divisible by k
if(k++==c){   //   If k and c are now equal (which means c is a prime number):
//   (and increase k by 1 afterwards for the next iteration with k++)
System.out.println((b+c)/2-a);
//    Print (b+c)//2-a with trailing newline
a=b;b=c;    //    Then set a=b and b=c for the next iteration
n--;}}}     //    And decrease n by 1


# Retina 0.8.2, 95 bytes

\d+
__¶$&$*#___
#(#*(_+))
$2¶$1_
}+\b(__+)\1+&_
M!&\b_+¶_+¶_+
(_+)¶\1(_+)¶\1(\2(_+))\4
$.3  Try it online! Explanation: \d+ __¶$&$*#___  On the first pass, convert the input to 2,n,3 where n is a unary run of #s while the primes are unary using _s. #(#*(_+))$2¶$1_  Replace n,p with p,n-1,p+1. +\b(__+)\1+$
$&_  Increment the last value until it becomes prime. }  Repeat the above until n=0. M!&\b_+¶_+¶_+  Extract overlapping windows of three primes. (_+)¶\1(_+)¶\1(\2(_+))\4$.3


Match each set of three primes as \1, \1+\2, \1+\2+\4+\4 and calculate \2+\4 in decimal; \1+\2+\4 is the average of the second and third primes so \2+\4 is the difference between that and the first prime.

(take((zipWith3(\x y z->div(x+y)2-z)=<<tail)=<<tail)[x|x<-[2..],all((0/=).mod x)[2..x-1]])


# J, 21 20 bytes

3(-~-:)+/\p:@i.@+&2


Try it online!

• + & 2: Add 2 to n.
• And then (@, composition), i.: Make a list of the first n+2 nonnegative integers.
• And then (@, composition), p:: Get the prime numbers of those indices.
• 3 ...\: Apply the inside verb to each three consecutive prime numbers.
• (-~-:)  + /: Insert the two subverbs between the prime numbers, turning p q r into p (-~-:) (q + r).
• q + r adds (+) q and r.
• (-~-:) is a hook; it halves (-:) the sum of q and r, and then subtracts (-) p from the result; ~ swaps the operands from their usual order.

# Python 3, 98 bytes

f=lambda n:n and f(n-1)+[(g(n+1)+g(n+2))//2-g(n)]or[]
g=lambda n,i=1,p=1:n and-~g(n-p%i,i+1,p*i*i)


Try it online!

I couldn't find a better way than using a helper function, g, (stolen from Lynn's amazing answer on the tips question) to get the nth prime.

However, with default rules, it would be 77 bytes.

# Wolfram Language (Mathematica), 40 bytes

(#2+#3)/2-#&@@Prime[#+{0,1,2}]&~Array~#&


Try it online!

• Completely based on another answer without citing the source. Feb 7, 2023 at 15:31
• Sorry i was wrong =( I'm going through hard times and CDCC is kinda self-help. I will react more thoughtfully. It's impossible to change now vote, until u edit answer. I'll do it if i can. Feb 7, 2023 at 16:57
• @lesobrod don't worry about the vote. I am sure you'll have fun here! I can assure you that this is a very nice community and you will learn crazy things about any language! Feb 7, 2023 at 17:02

# Charcoal, 41 bytes

Ｎθ≔¹ηＷ‹ⅉθ«≦⊕η¿⬤υ﹪ηκ«Ｆ‹⁴η⟦Ｉ⁻⊘⁺η↨υ⁰§υ±²⟧⊞υη


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

Ｎθ


Input n.

≔¹η


Start looking for primes after 1.

Ｗ‹ⅉθ«


Repeat until n results have been obtained.

≦⊕η


Increment the candidate prime.

¿⬤υ﹪ηκ«


If it is indeed prime, then:

Ｆ‹⁴η


If it is at least the third prime, then...

⟦Ｉ⁻⊘⁺η↨υ⁰§υ±²⟧


... output the difference of the average with the previous prime with the prime before.

⊞υη


Add the prime to the list.

# [Wolfram Language (Mathematica)], 42 bytes

ListConvolve[{1,1,-2}/2,Prime@Range[#+2]]&


Try it online!

• 37 bytes
– att
Feb 8, 2023 at 22:42

# Raku, 49 bytes

{(-*+(*+*)/2)(|grep(&is-prime,2..*)[^3+$++])xx$_}


Try it online!

Without the requirement for preceding elements, this could output the nth element for 42 bytes:

-*+(*+*)/2 o{grep(&is-prime,2..*)[^3+$_]}  Try it online! # Jelly, 12 bytes 3Ḷ+)ÆNḋ-,.,.  Try it online! This has to be possible in 11 bytes if a hardcoded dot product ties everything else I've come up with... 3Ḷ [0, 1, 2] + plus ) each [1 .. n], individually. ÆN Get the x'th prime for each x in that matrix, ḋ then return each row's dot product with -,.,. [-1, 0.5, 0.5].  # Wolfram Language (Mathematica), 53 47 bytes (#3+#2)/2-#&@@@Partition[Prime@Range[#+2],3,1]&  Thanks to @ZaMoC Try it online! • 47 bytes Feb 6, 2023 at 22:15 ## BSD/Linux command line, 52 bytes Requirements: primes 2|awk '{a=b;b=c;c=$0;$0=(c+b)/2-a}a'|head -$1


Try it online: there seems to be a bug in the version of awk on TIO which causes it to print blanks when printing $0 (implicitly or explicitly) and $0 is numeric. The version in my answer does work on my machines. Here's modified code with a workaround — obviously the workaround for the bug on TIO increases the length (by two bytes: an extra "").

## F#, 188 bytes

let x=Seq.initInfinite
let p n=n=2||Seq.forall(fun c->n%c<>0)[2..n-1]
let f n=x(fun i->n+i+1)|>Seq.find p
let s n=x(fun i->i+2)|>Seq.where p|>Seq.map(fun p->(f p+(f p|>f))/2-p)|>Seq.take n


Try it online!

Didn't think it would end up so big, to be honest. I wonder if my approach is maybe wrong... but it's all functional, stateless, and inefficent.

Anyway, a brief explanation:

x is a shorthand for Seq.initInfinite, which creates endless, lazy-evaluated sequences. p n determines if a number n is prime. f n gets the next prime number after n. s n is the main sequence function. First it creates a sequence of primes, then for each of them, gets the next prime and next-next prime, and calculates the average. Finally, it takes the first n` elements in the sequence.