23
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ is 13 a prime twin? \$\endgroup\$ – LiefdeWen Jul 24 '17 at 11:58
  • \$\begingroup\$ @LiefdeWen Yes, because it belongs to the pair (11, 13) \$\endgroup\$ – daniero Jul 24 '17 at 12:05

19 Answers 19

18
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ Beating Jelly and tying 05AB1E, nice \$\endgroup\$ – Stephen Jul 24 '17 at 11:39
  • 3
    \$\begingroup\$ Clever usage! +1 \$\endgroup\$ – Erik the Outgolfer Jul 24 '17 at 19:56
11
\$\begingroup\$

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.
\$\endgroup\$
7
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – kasperd Jul 25 '17 at 20:51
  • \$\begingroup\$ Yes, this will work just as well in Python 2. The 3 is part of the auto-generated SE post from TIO. \$\endgroup\$ – Dennis Jul 25 '17 at 21:04
5
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ Use ÌIÍ‚ instead of 40SÍ+ for -1 byte \$\endgroup\$ – Datboi Jul 24 '17 at 15:30
4
\$\begingroup\$

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)

<?=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.

\$\endgroup\$
3
\$\begingroup\$

Mathematica, 33 bytes

(P=PrimeQ;P@#&&(P[#+2]||P[#-2]))&

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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)

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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));
}

\$\endgroup\$
  • \$\begingroup\$ You don't need the var, the parentheses around the n in the function definition, etc. \$\endgroup\$ – Jared Smith Jul 24 '17 at 16:57
  • \$\begingroup\$ 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) \$\endgroup\$ – Taylor Scott Jul 24 '17 at 17:24
  • 1
    \$\begingroup\$ Thx to both of you \$\endgroup\$ – Serge K. Jul 24 '17 at 20:44
1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ 16 bytes with 3>0#.@p:0 2 _2&+ \$\endgroup\$ – miles Jul 24 '17 at 7:15
  • \$\begingroup\$ @miles nice. very clever use of base 2 to process the results. \$\endgroup\$ – Jonah Jul 24 '17 at 15:44
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Ruby, 38 + 6 = 44 bytes

Requires options -rprime.

->n{n.prime?&[n-2,n+2].any?(&:prime?)}

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ You can save a byte using & instead of && \$\endgroup\$ – Piccolo Jul 24 '17 at 19:22
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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;}
\$\endgroup\$
  • \$\begingroup\$ This can be golfed considerably by changing the names of both functions to 1 character each (eg a and b) \$\endgroup\$ – Skidsdev Jul 24 '17 at 10:16
  • 2
    \$\begingroup\$ Doesn´t PHP need the function keyword anymore? \$\endgroup\$ – Titus Jul 24 '17 at 13:15
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Hmm... I feel like [U+2U-2] could be much shorter, but I can't figure out how... \$\endgroup\$ – ETHproductions Jul 26 '17 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy