# Do I have a prime twin?

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 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 , so the shortest code in bytes wins!

• is 13 a prime twin? Jul 24, 2017 at 11:58
• @LiefdeWen Yes, because it belongs to the pair (11, 13) Jul 24, 2017 at 12:05
• This is OEIS A001097. Mar 23, 2021 at 8:18

# Brachylog, 9 8 bytes

ṗ∧4√;?+ṗ


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

• Beating Jelly and tying 05AB1E, nice Jul 24, 2017 at 11:39
• Clever √ usage! +1 Jul 24, 2017 at 19:56

# Jelly, 10 9 bytes

%6+_2_ÆP⁺


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.


# Python 3, 53 bytes

lambda n:sum((n+n%6-3)*n%k<1for k in range(2,4*n))==2


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).

• Wow. Such short code and yet so many special cases it must handle correctly. Any reason you say Python 3? As far as I can tell it also works in Python 2. Jul 25, 2017 at 20:51
• Yes, this will work just as well in Python 2. The 3 is part of the auto-generated SE post from TIO. Jul 25, 2017 at 21:04

# 05AB1E, 10 9 bytes

Saved 1 byte thanks to Datboi

ÌIÍ‚pZIp*


Try it online! or as a Test Suite

Explanation

Ì           # push input+2
IÍ         # push input-2
‚        # pair
p       # isPrime
Z      # max
Ip    # push isPrime(input)
*   # multiply

• Use ÌIÍ‚ instead of 40SÍ+ for -1 byte Jul 24, 2017 at 15:30

# Perl 6, 24 bytes

?(*+(0&(-2|2))).is-prime


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.

# PHP, 52 bytes

<?=($p=gmp_prob_prime)($n=$argn)&&$p($n+2)|$p($n-2);  without GMP, 84 bytes <?=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 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. # Mathematica, 33 bytes (P=PrimeQ;P@#&&(P[#+2]||P[#-2]))&  Try it online! # MATL, 11 bytes HOht_v+ZpAa  Output is 0 or 1. 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  # 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!

### 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) # Pyth, 14 12 11 bytes &P_QP-3+%Q6  Test Suite. Saved 3 bytes using the formula in @Dennis' answer. Saved 1 byte thanks to @Dennis. # Pyth, 14 bytes *Initial Solution &|P_ttQP_hhQP_  Test Suite. # Factor + math.primes, 42 bytes [| x | 0 2 -2 [ x + prime? ] tri@ or and ]  Try it online! Originally inspired by trying to golf Michael Chatiskatzi's answer, 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)) # 05AB1E, 8 bytes Port of Dennis' Jelly answer 6%+ÍIp-p  Try it online! or as a Test Suite Explanation 6% # n mod 6 + # add n Í # subtract 2 Ip- # subtract isPrime(n) p # isPrime  # JavaScript, 91 bytes, 81 bytes thanks to 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)); } • You don't need the var, the parentheses around the n in the function definition, etc. Jul 24, 2017 at 16:57 • I think you could edit your snippet to show the value of n beside the value of t(n) for increased clarity (Eg. 7: true) Jul 24, 2017 at 17:24 • Thx to both of you Jul 24, 2017 at 20:44 # 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  # J, 23 bytes 1&p:*.0<+/@(1 p:_2 2+])  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  • 16 bytes with 3>0#.@p:0 2 _2&+ Jul 24, 2017 at 7:15 • @miles nice. very clever use of base 2 to process the results. Jul 24, 2017 at 15:44 # Ruby, 38 + 6 = 44 bytes Requires options -rprime. ->n{n.prime?&[n-2,n+2].any?(&:prime?)}  Try it online! • You can save a byte using & instead of && Jul 24, 2017 at 19:22 # 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)) # 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! ## 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. • Hmm... I feel like [U+2U-2] could be much shorter, but I can't figure out how... Jul 26, 2017 at 14:45 # Husk, 8 bytes Vṗ(§e+-2  Try it online! # Factor + 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! # APL (Dyalog Unicode), 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! # Regex (ECMAScript or better), 483529 28 bytes -20 bytes thanks to H.PWiz ^(xx)?(?!(xx(x*))\3?\2+$)xxx


Try it online! - ECMAScript
Try it online! - Perl
Try it online! - Java
Try it online! - Python
Try it online! - Ruby
Try it online! - PCRE
Try it online! - .NET

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: ^(?!(xx+)\1+$)(?=(x{6})*(x*))xxx(?!(xx+)(?=\4*(x*)).*(?=\5\3$)\4+$)


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!

^(11)?(?!(11(1*))\3?\2+$)111  Try it online! - test cases only # 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;}

• This can be golfed considerably by changing the names of both functions to 1 character each (eg a and b) Jul 24, 2017 at 10:16
• Doesn´t PHP need the function keyword anymore? Jul 24, 2017 at 13:15

# Python 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!

# 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))