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? – LiefdeWen Jul 24 '17 at 11:58
• @LiefdeWen Yes, because it belongs to the pair (11, 13) – daniero Jul 24 '17 at 12:05

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 – Stephen Jul 24 '17 at 11:39
• Clever usage! +1 – Erik the Outgolfer Jul 24 '17 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. – kasperd Jul 25 '17 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. – Dennis Jul 25 '17 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 – Datboi Jul 24 '17 at 15:30

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 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. 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) 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. 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. – Jared Smith Jul 24 '17 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) – Taylor Scott Jul 24 '17 at 17:24 • Thx to both of you – Serge K. Jul 24 '17 at 20:44 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&+ – miles Jul 24 '17 at 7:15 • @miles nice. very clever use of base 2 to process the results. – Jonah Jul 24 '17 at 15:44 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 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 && – Piccolo Jul 24 '17 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)) 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 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) – Skidsdev Jul 24 '17 at 10:16
• Doesn´t PHP need the function keyword anymore? – Titus Jul 24 '17 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!

Japt, 13 bytes

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