Do I have a prime twin?

23

5

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!

user70974

Posted 2017-07-24T05:41:59.467

Reputation:

is 13 a prime twin? – LiefdeWen – 2017-07-24T11:58:03.467

@LiefdeWen Yes, because it belongs to the pair (11, 13) – daniero – 2017-07-24T12:05:17.043

Answers

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

Fatalize

Posted 2017-07-24T05:41:59.467

Reputation: 32 976

2Beating Jelly and tying 05AB1E, nice – Stephen – 2017-07-24T11:39:53.360

3Clever usage! +1 – Erik the Outgolfer – 2017-07-24T19:56:28.820

11

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.

Dennis

Posted 2017-07-24T05:41:59.467

Reputation: 196 637

7

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

Dennis

Posted 2017-07-24T05:41:59.467

Reputation: 196 637

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 – 2017-07-25T20:51:16.393

Yes, this will work just as well in Python 2. The 3 is part of the auto-generated SE post from TIO. – Dennis – 2017-07-25T21:04:31.443

5

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

Emigna

Posted 2017-07-24T05:41:59.467

Reputation: 50 798

1Use ÌIÍ‚ instead of 40SÍ+ for -1 byte – Datboi – 2017-07-24T15:30:56.713

4

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.

Titus

Posted 2017-07-24T05:41:59.467

Reputation: 13 814

3

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.

Mr. Xcoder

Posted 2017-07-24T05:41:59.467

Reputation: 39 774

3

Mathematica, 33 bytes

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

Try it online!

J42161217

Posted 2017-07-24T05:41:59.467

Reputation: 15 931

3

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

Luis Mendo

Posted 2017-07-24T05:41:59.467

Reputation: 87 464

2

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)

PunPun1000

Posted 2017-07-24T05:41:59.467

Reputation: 973

2

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

Serge K.

Posted 2017-07-24T05:41:59.467

Reputation: 171

You don't need the var, the parentheses around the n in the function definition, etc. – Jared Smith – 2017-07-24T16:57:20.077

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 – 2017-07-24T17:24:47.790

1Thx to both of you – Serge K. – 2017-07-24T20:44:04.593

2

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.

Sean

Posted 2017-07-24T05:41:59.467

Reputation: 4 136

1

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

Jonah

Posted 2017-07-24T05:41:59.467

Reputation: 8 729

16 bytes with 3>0#.@p:0 2 _2&+ – miles – 2017-07-24T07:15:50.187

@miles nice. very clever use of base 2 to process the results. – Jonah – 2017-07-24T15:44:04.583

1

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

Emigna

Posted 2017-07-24T05:41:59.467

Reputation: 50 798

1

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

Taylor Scott

Posted 2017-07-24T05:41:59.467

Reputation: 6 709

1

Ruby, 38 + 6 = 44 bytes

Requires options -rprime.

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

Try it online!

daniero

Posted 2017-07-24T05:41:59.467

Reputation: 17 193

1You can save a byte using & instead of && – Piccolo – 2017-07-24T19:22:38.917

1

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

Austin

Posted 2017-07-24T05:41:59.467

Reputation: 11

0

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

jahly

Posted 2017-07-24T05:41:59.467

Reputation: 31

This can be golfed considerably by changing the names of both functions to 1 character each (eg a and b) – Skidsdev – 2017-07-24T10:16:08.720

2Doesn´t PHP need the function keyword anymore? – Titus – 2017-07-24T13:15:10.613

0

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!

officialaimm

Posted 2017-07-24T05:41:59.467

Reputation: 2 739

0

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.

Justin Mariner

Posted 2017-07-24T05:41:59.467

Reputation: 4 746

Hmm... I feel like [U+2U-2] could be much shorter, but I can't figure out how... – ETHproductions – 2017-07-26T14:45:46.427