[Question]
  [
An Integer is *prime* if and only if it is positive and has exactly 2 distinct divisors: 1 and itself. A twin prime pair is made of two elements: `p` and `p±2`, that are both prime.
You will be given a positive integer as input. Your task is to return a truthy / falsy depending on whether the given integer belongs to a twin pair, following the standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") rules (the values need to be consistent).
## Test Cases
* Truthy (Twin Primes): `3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43`
* Falsy (not Twin Primes): `2, 15, 20, 23, 37, 47, 97, 120, 566`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
  
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 8 bytes
```
ṗ∧4√;?+ṗ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO6Y86lps86phlba8N5Pz/b2T5HwA "Brachylog – Try It Online")
### Explanation
```
ṗ           Input is prime
 ∧          And
  4√        A number whose square is 4 (i.e. -2 or 2)
    ;?+     That number + the Input…
       ṗ    …is prime
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes
```
%6+_2_ÆP⁺
```
[Try it online!](https://tio.run/##y0rNyan8/1/VTDveKP5wW8Cjxl3/DQ0MD7cfnpDmrfBwx/ZHDXMUQsoz8xQKijJzU4sVSgsUSvIVgEr0/gMA "Jelly – Try It Online")
### Background
With the exception of **(3, 5)**, all twin prime pairs are of the form **(6k - 1, 6k + 1)**.
Since **(6k - 1) + (6k - 1) % 6 - 3 = 6k - 1 + 5 - 3 = 6k + 1** and  
**(6k + 1) + (6k + 1) % 6 - 3 = 6k + 1 + 1 - 3 = 6k - 1**, given an input **n > 3**, it is sufficient to check whether **n** and **n + n % 6 - 3** are both prime.
This formula *happens to* work for **n = 3** as well, as **3 + 3 % 6 - 3 = 3** is prime and **3** is a twin prime.
### How it works
```
%6+_2_ÆP⁺  Main link. Argument: n
%6         Compute n%6.
  +        Add n to the result.
   _2      Subtract 2.
     _ÆP   Subtract 1 if n is prime, 0 if not.
           If n is not a prime, since (n + n%6 - 2) is always even, this can only
           yield a prime if (n + n%6 - 2 = 2), which happens only when n = 2.
        ⁺  Call ÆP again, testing the result for primality.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 53 bytes
```
lambda n:sum((n+n%6-3)*n%k<1for k in range(2,4*n))==2
```
[Try it online!](https://tio.run/##RckxDkAwGAbQmVP8i6SlhtIYRG9iqVAafKQYnL6YbC95@31OG8pgSVMbFrN2vSHUx7UyhgxJlZc8RTI30m6eZnIgbzAOrBAqBedaF@Eb/CMFVUrxOo6cJcvwKdq9w/k6PA "Python 3 – Try It Online")
### Background
All integers take one of the following forms, with integer **k**: **6k - 3**, **6k - 2**, **6k - 1**, **6k**, **6k + 1**, **6k + 2**.
Since **6k - 2**, **6k**, and **6k + 2** are all even, and since **6k - 3** is divisible by **3**, all primes except **2** and **3** must be of the form **6k - 1** or **6k + 1**. Since the difference of a twin prime pair is **2**, with the exception of **(3, 5)**, all twin prime pairs are of the form **(6k - 1, 6k + 1)**.
Let **n** be of the form **6k ± 1**.
* If **n = 6k -1**, then **n + n%6 - 3 = 6k - 1 + (6k - 1)%6 - 3 = 6k - 1 + 5 - 3 = 6k + 1**.
* If **n = 6k + 1**, then **n + n%6 - 3 = 6k + 1 + (6k + 1)%6 - 3 = 6k + 1 + 1 - 3 = 6k - 1**.
Thus, *if* **n** is part of a twin prime pair and **n ≠ 3**, it's twin will be **n + n%6 - 3**.
### How it works
Python doesn't have a built-in primality test. While there are short-ish ways to test a single number for primality, doing so for two number would be lengthy. We're going to work with divisors instead.
```
sum((n+n%6-3)*n%k<1for k in range(2,4*n))
```
counts how many integers **k** in the interval **[2, 4n)** divide **(n + n%6 - 3)n** evenly, i.e., it counts the number of divisors of **(n + n%6 - 3)n** in the interval **[2, 4n)**. We claim that this count is **2** if and only if **n** is part of a twin prime pair.
* If **n = 3** (a twin prime), **(n + n%6 - 3)n = 3(3 + 3 - 3) = 9** has two divisors (**3** and **9**) in **[2, 12)**.
* If **n > 3** is a twin prime, as seen before, **m := n + n%6 - 3** is its twin. In this case, **mn** has exactly four divisors: **1, m, n, mn**. 
Since **n > 3**, we have **m > 4**, so **4n < mn** and exactly two divisors (**m** and **n**) fall into the interval **[2, 4n)**.
* If **n = 1**, then **(n + n%6 - 3)n = 1 + 1 - 3 = -1** has no divisors in **[2, 4)**.
* If **n = 2**, then **(n + n%6 - 3)n = 2(2 + 2 - 3) = 2** has one divisor (itself) in **[2, 8)**.
* If **n = 4**, then **(n + n%6 - 3)n = 4(4 + 4 - 3) = 20** has four divisors (**2**, **4**, **5**, and **10**) in **[2, 16)**.
* If **n > 4** is even, **2**, **n/2**, and **n** all divide **n** and, therefore, **(n + n%6 - 3)n**. We have **n/2 > 2** since **n > 4**, so there are at least three divisors in **[2, 4n)**.
* If **n = 9**, then **(n + n%6 - 3)n = 9(9 + 3 - 3) = 81** has three divisors (**3**, **9**, and **21**) in **[2, 36)**.
* If **n > 9** is a multiple of **3**, then **3**, **n/3**, and **n** all divide **n** and, therefore, **(n + n%6 - 3)n**. We have **n/3 > 3** since **n > 9**, so there are at least three divisors in **[2, 4n)**.
* Finally, if **n = 6k ± 1 > 4** is not a twin prime, either **n** or **m := n + n%6 - 3** must be composite and, therefore, admit a proper divisor **d > 1**.
Since either **n = m + 2** or **m = n + 2** and **n, m > 4**, the integers **d**, **m**, and **n** are *distinct* divisors of **mn**. Furthermore, **m < n + 3 < 4n** since **n > 1**, so **mn** has at least three divisors in **[2, 4n)**.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ 9 bytes
Saved 1 byte thanks to *Datboi*
```
ÌIÍ‚pZIp*
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cI/n4d5HDbMKojwLtP7/N7IEAA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVvn/cE/l4d5HDbMKoioLtP5XKh3eb6VweL@STsx/Yy5TLnMuQ0MuQ2MuQyDDksvIksvYkMsEiIy5jLgMTbmMDLiMjLmMzblMzLksgUqAfFMzMwA)
**Explanation**
```
Ì           # push input+2
 IÍ         # push input-2
   ‚        # pair
    p       # isPrime
     Z      # max
      Ip    # push isPrime(input)
        *   # multiply
```
[Answer]
# [Perl 6](http://perl6.org/), 24 bytes
```
?(*+(0&(-2|2))).is-prime
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPvfXkNLW8NATUPXqMZIU1NTL7NYt6AoMzf1v7VCcWKlQnpRagFQoY5CnKGBgfV/AA "Perl 6 – Try It Online")
`*` is the argument to this anonymous function. `0 & (-2 | 2)` is the junction consisting of the numbers `0` AND either `-2` OR `2`. Adding `*` to this junction produces the junction of the number `*` AND either of the numbers `* - 2` OR `* + 2`. Calling the `is-prime` method on this junction returns a truthy value if `*` is prime AND either `* - 2` OR `* + 2` are prime. Finally, the `?` collapses the truthy junction to a boolean value, satisfying the consistent-return-values condition.
[Answer]
# PHP, 52 bytes
```
<?=($p=gmp_prob_prime)($n=$argn)&&$p($n+2)|$p($n-2);
```
without GMP, **84 bytes**
(using [my prime function from stack overflow](https://stackoverflow.com/a/39743570))
```
<?=p($n=$argn)&&p(2+$n)|p($n-2);function p($n){for($i=$n;--$i&&$n%$i;);return$i==1;}
```
Run as pipe with `-nF`. Empty output for falsy, `1` for truthy.
[Dennis´ great solution](https://codegolf.stackexchange.com/a/135300) ported to PHP, **56 bytes**
```
while($i++<4*$n=$argn)($n+$n%6-3)*$n%$i?:$s++;echo$s==3;
```
Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/d1f6d9fb6f701b41661aa2b3d66d617539f51c93).
[Answer]
# Mathematica, 33 bytes
```
(P=PrimeQ;P@#&&(P[#+2]||P[#-2]))&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfI8A2oCgzNzXQOsBBWU1NIyBaWdsotqYGSOsaxWpqqv0HSueV6Duk6TtUG@somOoomOsoGBoCMZBnCGJb6igYAbExUMwEhI1ruZD0GAFVADUZGQAxUIcxUIcJEFuCdIIETc3Mav8DAA "Mathics – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
HOht_v+ZpAa
```
Output is `0` or `1`.
[Try it online!](https://tio.run/##y00syfn/38M/oyS@TDuqwDHx/39DYwA "MATL – Try It Online")
### Explanation
```
H    % Push 2
O    % Push 0
h    % Concatenate horizontally: gives [2 0]
t_   % Push a negated copy: [-2 0]
v    % Concatenate vertically: [2 0; -2 0]
+    % Add to implicit input
Zp   % Isprime
A    % All: true for columns that only contain nonzeros
a    % Any: true if there is at least a nonzero. Implicit display
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~45~~ 44 bytes
```
.*
$*
11(1+)
$1¶$&¶11$&
m`^(11+)\1+$
1<`1¶1
```
Returns 1 if the input is a twin prime, 0 otherwise
[Try it online!](https://tio.run/##DYsxDsIwFEP3d45QhVZCdX7TKBI7l6hQGBgYYECcrQfoxcKXPNjP9vf5e30e/RRvrV9GwogUNZ0JOvYwHLsUBt7tHuV00xRA1@alejcyxQ/IkJtKqphYXEZCmTSTDCssheoTz3ld/w "Retina – Try It Online")
### Explanation
```
.*              
$*
```
Convert to Unary
```
11(1+)          
$1¶$&¶11$&
```
Put n-2, n, and n+2 on their own lines
```
m`^(11+)\1+$   
```
(Trailing newline) Remove all composites greater than 1
```
1<`1¶1          
```
Check if there are two consecutive primes (or 1,3 because 3 is a twin prime)
[Answer]
# [Pyth](http://pyth.readthedocs.io), ~~14 12~~ 11 bytes
```
&P_QP-3+%Q6
```
[Test Suite.](http://pyth.herokuapp.com/?code=%26P_QP-3%2B%25Q6&test_suite=1&test_suite_input=5%0A7%0A11%0A15%0A20%0A37&debug=0)
---
Saved 3 bytes using the formula in @Dennis' answer. Saved 1 byte thanks to @Dennis.
---
# [Pyth](http://pyth.readthedocs.io), 14 bytes \**Initial Solution*
```
&|P_ttQP_hhQP_
```
[Test Suite.](http://pyth.herokuapp.com/?code=%26%7CP_ttQP_hhQP_&input=9&test_suite=1&test_suite_input=3%0A%0A5%0A%0A7%0A%0A11%0A%0A13+%0A%0A17%0A%0A19%0A%0A2%0A%0A15%0A%0A20%0A%0A47%0A%0A9&debug=0&input_size=2)
[Answer]
# [Factor](https://factorcode.org/) + `math.primes`, 42 bytes
```
[| x | 0 2 -2 [ x + prime? ] tri@ or and ]
```
[Try it online!](https://tio.run/##HYyxCsIwFEV3v@LsYpFs6qCbuLiIU@kQasRimoSXB7bQf4@h2z3nwH3bXqOU5@N2vx75OgnOk8SpzkmGoIxWP/jYW5/X3VQ9usyptAsTC3sMO0NbYcsaz3SoDBeiYMOLrpjDJv9sor54mvIH "Factor – Try It Online")
Originally inspired by trying to golf [Michael Chatiskatzi's answer](https://codegolf.stackexchange.com/a/220617/62393), I've then modified it enough that I thought worth posting it as a separate answer.
### Explanation
This is a lambda function using the local variable `x` to refer to the element at the top of the stack when the function is called (its argument).
`[ x + prime? ]` defines a function that adds `x` to a number and checks if the result is prime. This is then applied using `tri@` to the three values `0`,`2`,`-2`, resulting in three booleans determining if `x`,`x+2` and `x-2` are primes. We combine the last two with `or`, and the result of this with the first with `and`.
The total function is then equivalent to `isprime(x+0) and (isprime(x+2) or isprime(x-2))`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/135293/47066)
```
6%+ÍIp-p
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fTFX7cK9ngW7B//9GlgA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##DYoxCoAwEAT7fYUErFTI3eUS4ltsFOxTCQG/4JtS5GFnYIoZGK/nRbe9T60W56V/tWzFquttn3pz62ECRQIRSEBDMjhDCGEgYJCCPVggCSEhj2W0xvgD)
**Explanation**
```
6%         # n mod 6
  +        # add n
   Í       # subtract 2
    Ip-    # subtract isPrime(n)
       p   # isPrime
```
[Answer]
# JavaScript, 91 bytes, 81 bytes thanks to [Jared Smith](https://codegolf.stackexchange.com/users/59429/jared-smith)
```
p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2))
```
**Explanation**
`p` tells wether the given number `n` is prime or not, and `t` tests given number `n` and `n±2`.
**Example**
```
var twinPrimes = [3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43];
var notTwinPrimes = [2, 15, 20, 23, 37, 47, 97, 120, 566];
p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2))
for (var n of twinPrimes) {
  console.log(n, ': ', t(n));
}
for (var n of notTwinPrimes) {
  console.log(n, ': ', t(n));
}
```
[Answer]
# Excel VBA, ~~102~~ 100 Bytes
No primality built-ins for VBA `:(`
### Code
Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs either `1` (truthy) or `0` (falsy) to the VBE Immediate window
```
a=[A1]:?p(a)*(p(a-2)Or p(a+2))
```
### Helper Function
```
Function p(n)
p=n>2
For i=2To n-1
p=IIf(n Mod i,p,0)
Next
End Function
```
---
## Alternatively, 122 Bytes
### Code
Recursive primality checking function based solution
```
a=[A1]:?-1=Not(p(a,a-1)Or(p(a-2,a-3)*p(a+2,a+1)))
```
### Helper Function
```
Function p(n,m)
If m>1Then p=p(n,m-1)+(n Mod m=0)Else p=n<=0
End Function
```
[Answer]
# J, 23 bytes
```
1&p:*.0<+/@(1 p:_2 2+])
```
[Try it online!](https://tio.run/##RYqxCsJAEAX7@4ohhcQE4u1uLscFBX8kWIhBLGLafP25nfCKecx8al1vA3La526I1/5yb4V9fijaL@dwuDMSGRHEEIeCFkwYfRY2LxRJaEQNy4yZ4pn/NE3h9Xx/WZvI8cet1h8 "J – Try It Online")
### how?
```
1&p:                               is the arg a prime?
    *.                             boolean and
                                   one of +2 or -2 also a prime
                     (1 p:_2 2+])  length 2 list of booleans indicating if -2 and +2 are primes
               @                   pipe the result into...
      0<+/                         is the sum of the elements greater than 0
                                   ie, at least one true
```
[Answer]
# Ruby, 38 + 6 = 44 bytes
Requires options `-rprime`.
```
->n{n.prime?&[n-2,n+2].any?(&:prime?)}
```
[Try it online!](https://tio.run/##KypNqvyfpmD7X9curzpPr6AoMzfVXi06T9dIJ0/bKFYvMa/SXkPNCiKuWfu/KLWwNLMoVUG9oECdq6BAQcNST8/IWFMvN7FAoVqhpqJGIbpCRyEtuiI2VqH2/7/8gpLM/Lzi/7pFYBMA "Ruby – Try It Online")
[Answer]
# JavaScript(ES6), 54 bytes
```
a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1
```
```
a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1
console.log("True")
console.log("---------------------")
console.log(a(3))
console.log(a(5))
console.log(a(7))
console.log(a(11))
console.log(a(13))
console.log(a(17))
console.log(a(19))
console.log(a(29))
console.log(a(31))
console.log(a(41))
console.log(a(43))
console.log("False")
console.log("---------------------")
console.log(a(2))
console.log(a(15))
console.log(a(20))
console.log(a(23))
console.log(a(37))
console.log(a(47))
console.log(a(97))
console.log(a(120))
console.log(a(566))
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
j ©[U+2U-2]dj
```
Returns `true` and `false` for whether or not the number is part of a prime twin pair.
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=aiCpW1UrMlUtMl1kag==&inputs=Mg==,Mw==,MTU=,NQ==,MjA=,Nw==,MjM=,MTE=,Mzc=,MTM=)
## Explanation
Implicit: `U` = input integer
```
j ©
```
Check if the input is prime (`j`), AND (`©`) ...
```
[U+2U-2]dj
```
Using the array `[U+2, U-2]`, check if any items are true (`d`) according to the primality function (`j`).
Implicit output of the boolean result of `is input prime AND is any ±2 neighbor prime`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
Vṗ(§e+-2
```
[Try it online!](https://tio.run/##yygtzv7/P@zhzukah5anausa/f//39AQAA "Husk – Try It Online")
[Answer]
# [Factor](https://factorcode.org/) + `math.primes`, 46 bytes
```
[ dup 2 [ + ] 2keep - [ prime? ] tri@ or and ]
```
**Demonstartion** of every state of the stack for the example number 43:
```
  43   dup    2  [ + ]  2keep    - [ prime? ] tri@   or   and
  
|    |     |    |  + |    2   |    | prime? |      |    |     | 
|    |     |  2 |  2 |   43   | 41 |     41 |    t |    |     | 
|    |  43 | 43 | 43 |   45   | 45 |     45 |    f |  t |     | 
| 43 |  43 | 43 | 43 |   43   | 43 |     43 |    t |  t |   t | 
```
[Try it online!](https://tio.run/##HYqxCoNAEAV7v@L1ooWxMkXsxCaNWInFohsUz3NZV0K@/nLYDMwwH5rs0NB37bupsLF6dtjJlhu56LrzCVE2@0XxhmcYMF@CAgNSjCg2ZkEW7Z5fMZmuNQ4F@RljKB/J@SXBRM4hD38 "Factor – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes
```
{∨/2∧/∊∘{(⊢~∘.×⍨)1↓⍳⍵}¨⍨|2(-,⊢,+)⍵}
 ∨/ ⍝ reduce by bitwise OR
   2∧/ ⍝ logical AND bit array, two at a time (overlapping)
     ∊∘{...}¨⍨ ⍝ for each, check if in list of primes
       (⊢~∘.×⍨)1↓⍳⍵ ⍝ find element of range that is not in matrix of composite numbers (list of primes)
         | ⍝ absolute value of array
           2(-,⊢,+)⍵ ⍝ create array (2-n, n, 2+n)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRx0r9I0edSzXf9TR9ahjRrXGo65FdUCG3uHpj3pXaBo@apv8qHfzo96ttYdWAAVqjDR0dYBKdLQ1QWJAQxSMudIUTIHYHIgNDUEESMQQzLUEEkYgwhgkYQImQLJGIEmQJiMDEAESMgZpMAERlmCtYBlTMzMA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Regex (ECMAScript or better), ~~48~~ ~~35~~ ~~29~~ 28 bytes
*-20 bytes thanks to [H.PWiz](https://chat.stackexchange.com/transcript/message/57424541#57424541)*
```
^(xx)?(?!(xx(x*))\3?\2+$)xxx
```
[Try it online!](https://tio.run/##TY@9bsIwFEZfBaIK7iVNSGjVAddk6sDC0I6llaxwcdwax7INuPw8exqGSp2@4XzS0fkSB@Frp2zIvFUbcrvWfNNP57ih4@CV5Eu0ACe@mE66T4gRK6iG/UKcIK4fqvUsvcMYYzeZnjAP7VtwykjA3GtVEzzdZ4@IzPOCHRulCUBzR2KjlSFAHHKz1xrPkuvcW60CjLMxMrUFMFzmmowMDS5ml4vyK7ECxa1wnpYmgHwvPhD/AP0HZlFW5fyGMTSuPSZLcxBabQZOGEnzQZJqtm0dMPXMiak0xV6YxCR3ZEkEUJjvRKgbcIhnPxrZPinAraJkdh98cP2FXa9dkZVFUfwC "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript  
[Try it online!](https://tio.run/##RU7BasMwDP0VrZjGWhJid/Qyx00K3XWn3ZbOdKUBg9dmdgYexvv1zM0Ku0h6T096bzhZs54@voFYAcFcjgcDpBIJynq3fdluIvQXS4mTTNQbgQF0nxCGwerzCIvuvBARWiPdYPRIszIr3Ne7G9OJKkpecDx9XkXNP8sSj49Eobj@csnxYFtTrzC05pXvZapsL26@@gaJruW8TlOeY9A9UJr5DDwkESLIH6iIrTAQt1zO4eZsKTgXf1mJFjFGpZ6ed0pNb9R7bGhzlzr194jdQ9OtcoLe@2liJWeM/QI "Perl 5 – Try It Online") - Perl  
Takes its input in unary, as a string of `x` characters whose length represents the number.
Commented and indented:
```
^                 # tail = N = input number
# Assert either that N-2 and N are prime, or that N and N+2 are prime.
(xx)?             # tail -= 2, optionally
# Assert that neither tail nor tail+2 are composite. For testing that they are both prime,
# this has false positives for tail=0, tail=1, and tail=2.
(?!               # Assert that the following can't match:
    (xx(x*))      # \2 = any number >= 2; \3 = \2 - 2
    \3?           # tail -= \3, optionally; if this is done, we're asserting that tail+2 is
                  #             composite (divisible by \2 with a quotient >= 3), otherwise
                  #             we're asserting tail is composite (quotient >= 2).
    \2+$          # Assert that tail is positive and divisible by \2
)
xxx               # Assert that tail >= 3, preventing the false positives.
                  # The "quotient >= 3" requirement above is why tail=2 can be one of them,
                  # as it prevents 2+2 from being seen as composite.
```
## 29 bytes
```
^                  # tail = N = input number
# Assert either that N-2 and N are prime, or that N and N+2 are prime.
(xx)?              # tail -= 2, optionally
# Assert that neither tail nor tail+2 are composite. For testing that they are both prime,
# this has false positives for tail=0 and tail=1.
(?!                # Assert that the following can't match:
    (xx)?          # tail -= 2, optionally; if this is done, we're asserting that tail is
                   #            composite, otherwise we're asserting tail+2 is composite.
    (x*)           # \3 = S-2, where S is a potential divisor to test against M = tail+2;
                   # tail -= \3
    (\3xx)+$       # assert that tail is positive and divisible by \3+2, which is
                   # equivalent to asserting M is divisible by S with a quotient >= 2
)
xx                 # Assert that tail >= 2, preventing the false positives.
```
## 48 bytes
This misses the fact that we can switch between testing N-2 and N or testing N and N+2. Instead, this regex switches between testing N and N-2 or testing N and N+2, which results in tests not having enough in common to be collapsed together.
```
^   # tail = N = input number
(
    # Assert that neither N nor N-2 are composite. But we want N and N-2 to be prime, so
    # this gives false positives for 0, 1, and 2.
    (?!              # Assert that the following can't match:
        (xx)?        # tail -= 2, optionally
        (xx+)        # \3 = any number >= 2
        \3+$         # Assert that tail is positive and divisible by \3
    )
|   # or...
    # Assert that neither N nor N+2 are composite. But we want N and N+2 to be prime, so
    # this gives false positives for 0 and 1.
    (?!              # Assert that the following can't match:
        (xx(x*))     # \4 = any number >= 2; \5 = \4 - 2
        \4*(xx)?\5$  # Assert that either tail or tail+2 is positive and divisible by \4
    )
)
xxx                  # Block the false positives on every number less than 3
```
## 51 bytes (not golfed at all)
```
^                      # tail = N = input number
(?!(xx+)\1+$)          # Assert that N is not composite. But we want N to be prime,
                       # so this gives false positives for 0 and 1.
(
    (?!xx(xx+)\3+$)    # Assert that N-2 is not composite. But we want N-2 to be prime, so this
                       # gives false positives for 0, 1, and 2.
|   # or...
    (?!(x*)(xx\4)+$)   # Assert that N+2 is not composite. Has no false positives for primality.
)
xxx                    # Block the false positives on every number less than 3
```
# Regex (ECMAScript), 67 bytes
Just for kicks, here is a port of [Dennis's Jelly algorithm](https://codegolf.stackexchange.com/a/135293/47066):
```
^(?!(xx+)\1+$)(?=(x{6})*(x*))xxx(?!(xx+)(?=\4*(x*)).*(?=\5\3$)\4+$)
```
[Try it online!](https://tio.run/##Tc9Nb8IwDAbgvwIVArtdS7sxDmSB0w5cOGzHdZMiMG22kEZJgIyP394VTZN2tJ/Xst5PcRBubaXxqTNyQ3bX6C/6bi3XdOy9UPUcDMCJz8dx@wGLPoSQYFkkA4QFh3CeXjGGECOGEP64k3Lyu83i2/BYPgywnHRHbTw@YeabV2@lrgAzp@SaYHqXThCZ4zk71lIRgOKWxEZJTYDY53qvFJ4rrjJnlPQwSkfI5BZA8ypTpCtf4/z@cpFuJVYguRHW0VJ7qN7yd8Q/oP@g58WimN0YfW2bY7TUB6HkpmeFrmjWixLFto0FJp84MZkk2D2MQpRZMiQ8SMx2wq9rsIhnNxyarpKHW4uCmb133nYRdr22eVrkef4D "JavaScript (SpiderMonkey) – Try It Online")
```
^                      # tail = N = input number
(?!(xx+)\1+$)          # Assert N is not composite
(?=(x{6})*(x*))        # \3 = N % 6
xxx                    # assert N>=3; tail -= 3
# Assert tail + \3 is not composite
(?!                    # Assert the following can't match:
    (xx+)              # \4 cycles through all values such that 2 <= \4 <= tail,
                       #    and is tested as a possible divisor of tail + \3
    (?=\4*(x*))        # \5 = tail % \4
    .*(?=\5\3$)        # tail = \5 + \3
    \4+$               # Assert that tail is positive and divisible by \4
)
```
### \$\large\textit{Anonymous functions}\$
# JavaScript (ES6), 50 bytes
```
n=>/^(..)?(?!(..(.*))\3?\2+$).../.test(Array(n+1))
```
[Try it online!](https://tio.run/##Tc1BbsIwEIXhqwCqYKZRjEN3uE7UJRsuUFrJahxnWndi2QaEgLOn6aJSV2/xSe//NCeTPiKFXKZArY3fA3/Zy9jpkXW9fgchsIFmPi2IR8TDU3PYFA8ohFiLbFOGlxjNBbioEMekpTr35C2A19Ga1hNbQJxrPnqPV6e9SMFThlW5QkUdAGsnvGWXe6w3txulvdkD6WBisjvO4F7lG@If2P/AddVU21/G3MfhvNjxyXhqZ9Gws9vZovCqGyIoetZWUVHgFOyAEK9puQyRphdUSVcqHHPKcRJ1v4@yrKSUPw "JavaScript (SpiderMonkey) – Try It Online")
# Ruby, 41 bytes
```
->n{?x*n=~/^(xx)?(?!(xx(x*))\3?\2+$)xxx/}
```
[Try it online!](https://tio.run/##PY7NDoIwEITvPsViTGg1LQWPWHkQQBMjP02axUCNNUZfHReiHNruTOebbH@/PMdaj@KIr8xvUX@iE/OeZywL6GV@y3mxz4pkt@He@@g9Gq1SeLTGVmB1U7lhBWBqsLmIS63XBa5T@rC5klIkZQoVXilBjhxu1jgWipD/EGkrbFzL@CEhJieesAWpux4QDMJkStedDYsVl3IKLpJyc1edI4E0mGDa73Z3w9xDno5J9wYd4L96uumMSsRKqS8 "Ruby – Try It Online")  
[Try it online!](https://tio.run/##DcXBCkVAFAbgvac4U7fMwR3FyoJ5ENyiKAs6ptSv4b768G0@d4xnmKkO32bzFslW//OfBthqq941EuautF2RfhhAfgc37cfiJopF4kiEdGVMUbJZByFPFy5qkZFSc4u@pzs8 "Ruby – Try It Online") - test cases only
### \$\large\textit{Full programs}\$
# [Retina](https://github.com/m-ender/retina), 34 bytes
```
.*
$*
^(11)?(?!(11(1*))\3?\2+$)111
```
[Try it online!](https://tio.run/##DYoxCgIxFAX7uYWwQpIF8f2/2ZAqpZdYRAsLGwvx/vHDg5mB93393p/nPKfbY14KS@GepDzSOAWTSs6Hj8PWJUua06k0JOQopGMdF1vMMVSxK@Z4Y2v0uETXff8D "Retina 0.8.2 – Try It Online") - test cases only
[Answer]
# PHP, 85 bytes **24 bytes thanks to Mayube**
```
e($n){return f($n)&&((f($n-2)||f($n+2)))
f($n){for($i=$n;--$i&&$n%$i;)return $i==1;}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 75 bytes
```
lambda x:p(x)*(p(x-2)|p(x+2))
p=lambda z:(z>1)*all(z%i for i in range(2,z))
```
[Try it online!](https://tio.run/##XYmxCoMwFEV3v@IthXetBc0YiF/iErFpH8QkBAcN/nvq4NTlHDgnHds3BlWdmaq367xY2nXiHS1ffCmcl54KaJK5f9FcxgGt9Z7LQ8jFTEISKNvwebPqClD/4tD30A2JI8cCnbKEjaT@AA "Python 2 – Try It Online")
[Answer]
# Excel, 84 bytes
Current Excel 365:
```
=LET(x,SEQUENCE(A1+2),(SUM((MOD(A1,x)=0)*1)=2)*(SUM((MOD(A1+MOD(A1,6)-3,x)=0)*1)=2))
```
Future Excel (73 bytes):
```
=LET(p,LAMBDA(a,SUM((MOD(a,SEQUENCE(a))=0)*1)=2),p(A1)*p(A1+MOD(A1,6)-3))
```
]