[Question]
  [
[Bertrand's Postulate](https://en.wikipedia.org/wiki/Bertrand%27s_postulate) states that for every integer **n ≥ 1** there is at least one prime **p** such that **n < p ≤ 2n**. In order to verify this theorem for **n < 4000** we do not have to check 4000 cases: The *Landau trick* says it is sufficient to check that 
```
2, 3, 5, 7, 13, 23, 43, 83, 163, 317, 631, 1259, 2503, 5003
```
are all prime. Because each of these numbers is less than twice its predecessor each interval **{y : n < y ≤ 2n}** contains at least one of those prime numbers. 
This sequence of numbers are the [Bertrand Primes (OEIS A006992)](http://oeis.org/A006992) and they are defined as follows:
```
a(1) = 2
a(n) = largest prime below 2a(n-1)
```
### Challenge
Implement this sequence. You may write
* a function or program that given some **n** returns **a(n)** (0 or 1 indexed),
* a function or program that given some **n** returns the first **n** (or **n-1** or **n+1**) entries of this sequence,
* an infinite list or stream or generator or similar equivalent in your langauge.
  
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 32 bytes
```
k=2
do k=primes(k+k)(end)until 0
```
Keeps printing the values indefinitely (each value is preceded by `k =`).
[Try it online!](https://tio.run/##y08uSSxL/f8/29aIKyVfIdu2oCgzN7VYI1s7W1MjNS9FszSvJDNHweD/fwsA)
---
# [Octave](https://www.gnu.org/software/octave/), 42 bytes
```
k=2
for i=2:input('')k=primes(k+k)(end)end
```
Takes **n** as input and outputs the **n** first values (each value is preceded by `k =`).
[Try it online!](https://tio.run/##y08uSSxL/f8/29aIKy2/SCHT1sgqM6@gtERDXV0z27agKDM3tVgjWztbUyM1L0UTiP//twAA)
---
# [Octave](https://www.gnu.org/software/octave/), 51 bytes
```
k=2;for i=2:input('')k=primes(k+k)(end);end
disp(k)
```
Similar to [Luis Mendo's MATL answer](https://codegolf.stackexchange.com/a/155673/61405). Takes **n** as input and outputs **a(n)** (1-indexed).
[Try it online!](https://tio.run/##y08uSSxL/f8/29bIOi2/SCHT1sgqM6@gtERDXV0z27agKDM3tVgjWztbUyM1L0XTGkhwpWQWF2hka/7/bwEA)
---
# [Octave](https://www.gnu.org/software/octave/), 60 bytes
```
k=2;for i=2:input('')k*=2;while~isprime(--k)
end
end
disp(k)
```
Takes **n** as input and outputs **a(n)** (1-indexed).
[Try it online!](https://tio.run/##y08uSSxL/f8/29bIOi2/SCHT1sgqM6@gtERDXV0zWwsoWp6RmZNal1lcUJSZm6qhq5utyZWalwLGKUBRjWzN//8tAA)
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
_4&(p:+:)2:
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/@NN1DQKrLStNI2s/mtyKekpqKeBJNUVdBRqrRTSirm4UpMz8hXSFAwN/gMA "J – Try It Online")
0-indexed.
```
_4&(p:+:)2:  Input: integer n
         2:  Constant 2
_4&(    )    Repeat n times
      +:       Double
_4  p:         Find the largest prime less than the double
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
Saved one byte thanks to Martin Ender.
0-indexed.
```
Nest[-NextPrime[-2#]&,2,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6hg@98vtbgkWtcvtaIkoCgzNzVa10g5Vk3HSAdI/nfJjwYK5pVE5@koKCno2iko6SgkOuTF6ihUA0UMdBSMDGpj/wMA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~7~~ 6 bytes
```
$F·.ØØ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fxe3Qdr3DMw7P@P/fBAA "05AB1E – Try It Online")
---
1-indexed answer (unless 0 is supposed to output 1), explanation:
```
$       # Push 1 and input (n)...
 F      # n-times do... 
  ·     # Double the current prime (first iteration is 1*2=2).
   .ØØ  # Find prime slightly less than double the current prime.
```
---
It's 1-indexed because all iterations have a 'dummy' iteration with `n=1`.
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f p|sum(gcd p<$>[1..p-1])<p=p:f(2*p)|1>0=f$p-1
f 2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoKa4NFcjPTlFocBGxS7aUE@vQNcwVtOmwLbAKk3DSKtAs8bQzsA2TQUozJVjm6Zg9D83MTNPwVahoCgzr0RBRaEkMTtVwdBEIee/oQEA "Haskell – Try It Online")
Outputs an infinite list.
---
# [Haskell](https://www.haskell.org/), 40 bytes?
```
f p|mod(2^p-2)p<1=p:f(2*p)|1>0=f$p-1
f 2
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoCY3P0XDKK5A10izwMbQtsAqTcNIq0CzxtDOwDZNpUDXkCvHNk3B6H9uYmaegq1CQVFmXomCikJJYnaqgqGJQs5/QwMA "Haskell – Try It Online")
This works if Bertrand's primes don't contain any [Fermat pseudoprimes for 2](http://oeis.org/A001567).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
2ḤÆp$¡
```
[Try it online!](https://tio.run/##y0rNyan8/9/o4Y4lh9sKVA4t/P//v6ExAA "Jelly – Try It Online")
0-indexed.
## Explanation
```
2ḤÆp$¡  Main link. Input: n
2       Constant 2
    $¡  Repeat n times
 Ḥ        Double
  Æp      Find the largest prime less than the double
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
1i:"EZq0)
```
Inputs **n**, outputs **a**(**n**), 1-indexed.
[Try it online!](https://tio.run/##y00syfn/3zDTSsk1qtBAE8g0AAA "MATL – Try It Online")
### Explanation
```
1       % Push 1
i       % Push input n
:"      % Do the following that many times
  E     %   Multiply by 2
  Zq    %   Primes up to that
  0)    %   Get last entry
        % End (implicit). Display (implicit)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 10 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü☼┌τ,æ▒ìn(
```
[Run test cases](https://staxlang.xyz/#c=%C3%BC%E2%98%BC%E2%94%8C%CF%84%2C%C3%A6%E2%96%92%C3%ACn%28&i=1%0A%0A2%0A%0A3%0A%0A13%0A%0A14&a=1&m=1)
This problem has exposed a bug in stax's implementation of `:p`, which is an instruction that gets the greatest prime less than its input. If it worked correctly, there would be a 5 6 byte solution. But alas, it does not, and there is not. As the language's creator, I will fix it, but it seems kind of cheap to fix and use it after the problem was posted.
Anyway, here is the corresponding ascii representation of the program above.
```
ODH{|p}{vgs
```
It's a relatively straight-forward implementation of the problem statement. The only thing possibly interesting about it is the use of the `gs` generator form. Generators are a family of constructions that combine an initial condition, a transform, and a filter, to produce one or more satisfying values. In this case, it's used in place of the broken `:p` instruction.
```
O               Push integer 1 underneath the input number.
 D              Pop the input and repeat the rest of the program that many times.
  H             Double number.
   {|p}         Predicate block: is prime?
       {vgs     Decrement until the predicate is satisfied.
                Output is implicitly printed.
```
*Edit:* [here](https://staxlang.xyz/#c=ODH%5E%3Ap&i=1%0A%0A2%0A%0A3%0A%0A13%0A%0A14&a=1&m=1)'s the 6 byte solution, but it requires a bug-fix that was only applied after this challenge was posted.
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
r=m=k=P=2
while k:
 P*=k;k+=1
 if k>m:print r;m=r*2
 if P%k:r=k
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8g21zbbNsDWiKs8IzMnVSHbikshQMs22zpb29aQSyEzTSHbLteqoCgzr0ShyDrXtkjLCCwaoJptVWSb/f8/AA "Python 2 – Try It Online")
Prints forever.
Uses the Wilson's Theorem prime generator even though generating primes forward is clunky for this problem. Tracks the current largest prime seen `r` and the doubling boundary `m`.
Two bytes are saved doing `P*=k` rather than `P*=k*k` as usual, as the only effect is to claim that 4 is prime, and the sequence of doubling misses it. 
[Answer]
## CJam (15 bytes)
```
2{2*{mp},W=}qi*
```
[Online demo](http://cjam.aditsu.net/#code=2%7B2*%7Bmp%7D%2CW%3D%7Dqi*&input=6). Note that this is 0-indexed.
---
A more efficient approach would be to search backwards, but this requires one character more because it can't use implicit `,` (range):
```
2{2*,W%{mp}=}qi*
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ ~~14~~ ~~13~~ 12 bytes
Two solutions for the price of one, both 1-indexed.
---
## Nth Term
Finally, a challenge I can write a working solution for using `F.g()`.
```
_ôZ fj Ì}g°U
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=X/RaIGZqIMx9Z7BV&input=OA==)
```
                 :Implicit input of integer U
_       }g       :Starting with the array [0,1] take the last element (Z),
                 :pass it through the following function
                 :and push the returned value to the array
 ôZ              :  Range [Z,Z+Z]
    fj           :  Filter primes
       Ì         :  Get the last item
          °U     :Repeat that process U+1 times and return the last element in the array
```
---
## First N Terms
```
ÆV=ôV fj Ìª2
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=xlY99FYgZmogzKoy&input=OA==)
```
                 :Implicit input of integer U
                 :Also makes use of variable V, which defaults to 0
Æ                :Create range [0,U) and pass each through a function
  ôV             :  Range [V,V+V]
     fj          :  Filter primes
        Ì        :  Get the last item
         ª2      :  Logical OR with 2, because the above will return undefined on the first iteration
 V=              :  Assign the result of the above to V
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
a(n)=if(n<2,2,precprime(2*a(n-1)))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P1EjT9M2M00jz8ZIx0inoCg1uaAoMzdVw0gLKKNrqKmp@T8tv0gjT8FWwVBHwchARwEon1cCFFBS0LUDEiADgIoA "Pari/GP – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
n=2
while 1:
 if all(n%i for i in range(2,n)):print n;n*=2
 n-=1
```
[Try it online!](https://tio.run/##DcuxCoAgFAXQva@4S6CRg46GH@OQ@UCuIkL49dbZT5sjVzrTZptrMbjtzVJuWL9BEmIpirsg1Q6BED3yuZU7qbVvXTjAi8ffQBPsWh8 "Python 2 (PyPy) – Try It Online") Prints the sequence indefinitely
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
a 1=2
a n=last[p|p<-[2..2*a(n-1)],all((>0).mod p)[2..p-1]]
```
[Try it online!](https://tio.run/##FcmxDoMgEADQ3a@4ERohwiwsfoZhuESipud5kRv777Qd3vQObO9K1DtCSHFA4ETYdJWPzG6N3scXGnbBlhGJjMmT9de9gdh/igul9AtPhgR71eVmrawNck4gz8kKHvDnqbj1MH0B "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 68 bytes
Prints the sequence indefinitely (you have to click "Run" the second time to stop the execution).
```
k=2
while 1:
 print k;k+=k
 while any(k%u<1for u in range(2,k)):k-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9vWiKs8IzMnVcHQikuhoCgzr0Qh2zpb2zabSwEinphXqZGtWmpjmJZfpFCqkJmnUJSYl56qYaSTralpla1ra/j/PwA "Python 2 – Try It Online")
### [Python 3](https://docs.python.org/3/), 90 bytes
Returns the nth term.
```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-1,i+1,p*i*i) 
a=lambda n:n and f(2*a(n-1))[-1]or 1
```
[Try it online!](https://tio.run/##PYtBCsIwEADvfcVSEJJ0A656CsSPhBxWanRBt6H00tfH9OJlLjNT9@296LW1Ej/8fcwMihIJa6SgLp0z6wz1JC5JnopRTyhT106cWBj4fwWFIy3m4vjIrE2e8rICtdKpIAor6@tpCIFuNgxQV9HNKI7@PmKfrG0/ "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~97~~ ~~87~~ ~~86~~ ~~80~~ 79 bytes
* Saved ten bytes by inlining a non-primality checking function `P` into the main loop.
* Saved a byte by moving the `printf` call.
* Saved six bytes by returning the `i`-th sequence entry (0-indexed) instead of outputting a never-ending stream.
* Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat).
```
f(p,r,i,m,e){for(r=2;p--;)for(e=0,i=r+r;e=m=!e;r=i--)for(;i-++m;e=e&&i%m);p=r;}
```
[Try it online!](https://tio.run/##JYxBCsMwDATf0kCChSUw7VHVB/yL4shBB6dG9Fb6didtjzszbKGtlDFq6Oho2FDhXZ8eXK7ciRi@QyWhiUdnlSYXZRcj@ik2irGdXJfF5gbcxfkz2sP2kP9XWRLn@y1xd9tfNUzzihPWkGMEgDM@AA "C (gcc) – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/attache), 38 bytes
```
{If[_,Last[Series[Prime,2*$[_-1]]],2]}
```
[Try it online!](https://tio.run/##SywpSUzOSP3vkpqWmZcarZKm87/aMy06XscnsbgkOji1KDO1ODqgKDM3VcdISyU6XtcwNjZWxyi29n8sF1A4r0TB1k4hTDkNRBlYGRr/BwA "Attache – Try It Online")
0-based; returns the `n`th Bertrand prime.
There is currently no builtin to find the previous/next primes, so I use the `Series` builtin to calculate all primes up to `2*$[_-1]`. This last expression uses implicit recursion (bound to `$`) to easily define the recurrence relation. The if condition is used to determine a base condition.
[Answer]
# [Perl 6](http://perl6.org/), 35 bytes
```
2,{(2*$_,*-1...&is-prime).tail}...*
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4FBQlJmbWqxg@99Ip1rDSEslXkdL11BPT08ts1gXLKepV5KYmVMLFNL6b61QnAjXEx1nZBBr/R8A "Perl 6 – Try It Online")
This expression is an infinite list of Bertrand primes.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 39 bytes
```
.K`_
"$+"{`_
__
+`^(?=(..+)\1+$).
*\`_
```
[Try it online!](https://tio.run/##K0otycxLNPz/X887IZ5LSUVbqRpIx8dzaSfEadjbaujpaWvGGGqraOpxcWnFJMT//28JAA "Retina – Try It Online") Explanation:
```
.K`_
```
Start with 1.
```
"$+"{`
```
Repeat the loop using the input as the loop count.
```
_
__
```
Double the value.
```
+`^(?=(..+)\1+$).
```
Find the highest prime less than the value.
```
*\`_
```
Print it out.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51 + 7 (-rprime) = 58 bytes
```
->n{x=2
n.times{x=(x..2*x).select(&:prime?)[-1]}
x}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vusLWiCtPryQzN7UYyNao0NMz0qrQ1CtOzUlNLtFQsyooAkrZa0brGsbWclXU/i8oLSlWSIs2NI79//9ffkFJZn5e8X/dIrAyAA "Ruby – Try It Online")
A lamba accepting `n` and returning the `nth` Bertrand prime, 0-indexed. There's not much here, but let me ungolf it anyway:
```
->n{
  x=2                       # With a starting value of 2
  n.times{                  # Repeat n times:
    x=(x..2*x)              # Take the range from x to its double
      .select(&:prime?)[-1] # Filter to only primes, and take the last
  }
  x                         # Return
}
```
# [Ruby](https://www.ruby-lang.org/), 48 + 7 = 55 bytes
```
x=2
loop{puts x
x*=2
loop{(x-=1).prime?&&break}}
```
[Try it online!](https://tio.run/##KypNqvz/v8LWiCsnP7@guqC0pFihgqtCCyagUaFra6ipV1CUmZtqr6aWVJSamF1b@////3/5BSWZ@XnF/3WLwJIA "Ruby – Try It Online")
For fun, here's an infinite-loop solution. It prints as it goes, and requires an interrupt. Depending on exactly when you interrupt, you may or may not see the output. Ungolfed:
```
x=2
loop{
  puts x
  x*=2
  loop{
    (x-=1).prime? && break
  }
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
Takes input from user as N, returns Nth element of the sequence (0-indexed).
```
{¯4⍭2×⍵}⍣⎕⊢2
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/1ofUmj3rXGh2e/qh3a@2j3sWP@qY@6lpkBJL9z5nGZcAFJAxBhBGIMAYRJiDCFESYAQA "APL (Dyalog Extended) – Try It Online")
Explanation:
```
{¯4⍭2×⍵}⍣⎕⊢2 ⍝ Full program
          ⎕   ⍝ Get input from user - call it 'N'
         ⍣ ⊢2 ⍝ Repeat the left function N times, beginning with 2
    2×⍵       ⍝ Double the function input
 ¯4⍭          ⍝ Find the largest prime less than above
```
[Answer]
# [R](https://www.r-project.org/), 87 bytes
# Given `n` outputs `a(n)`
```
j=scan();n=2;while(j-1){for(i in (n+1):(2*n)){n=ifelse(any(i%%2:(i-1)<1),n,i)};j=j-1};n
```
[Try it online!](https://tio.run/##DctNCoAgEAbQq7QRZvpZKK00DxOhNCJfUIsI8ezm/r27teSfYwexgzfuPSUHSovmEq@bZBAMhEmzJTOCucBLDPkJtOMjUcpYkq43zTNm4eqS77s6NL22Hw "R – Try It Online")
I'm still working on "Given n output a(1), a(2)... a(n)". I thought I could just modify this code slightly, but it seems more difficult than that.
]