# Introduction

We define twin primes as two natural numbers p,p+2 which both are prime.

Example: 5 and 7 are twin primes.

Let's define the twin number of some set of numbers as the number of twin prime numbers in that set

Example: {6,7,11,13,18,29,31} has a twin number 4, since there are four twin primes; 11,13 and 29,31.

# Program

Input: A number n

Output: The twin number of the set of all natural numbers below n

# Scoring

This is , so lowest bytes wins.

• Do you have some test cases? – Suever Jun 14 '16 at 0:42
• @CᴏɴᴏʀO'Bʀɪᴇɴ Natural number must also be whole numbers, and I assume he only wants us to deal with whole number primes – MayorMonty Jun 14 '16 at 1:06
• I'm not sure I understand the definition. The example set seems to have 4 twin primes. Are we supposed to count the number of pairs? If so, does 3, 5, 7 count as two pairs? What if one of the primes is in the set, but the other one isn't? – Dennis Jun 14 '16 at 1:12
• OK, I'm reopening, but a few test cases would still be helpful. – Dennis Jun 14 '16 at 1:25
• I think this is a duplicate of Find the Nth pair of twin primes. This one has you count them and that one has you generate them counting up, but the core process of enumerating and checking twin primes is the same. – xnor Jun 14 '16 at 2:42

# MATL, 7 bytes

qZqd2=s


This solution exploits the fact that the prime gap (the difference between successsive prime numbers) is always >= 2 (with the exception being the gap between 2 and 3). Because of this fact, all twin primes will be successive prime numbers. In this solution we just compute the differences between all primes less than the input n and count how many of these differences are equal to 2.

Try it Online

Explanation

    % Implicitly grab input, N
q   % Subtract one from the input (N-1)
Zq  % Get an array of all primes <= (N-1)
d   % Compute successive differences (prime gaps)
2=  % Create a boolean array indicating which prime gaps are equal to 2
s   % Count the TRUE values in this array to determine the twin number
% Implicitly display the result


If you instead want the not the number of pairs but the number of primes that are part of a pair, the following would work

qZqt!-|H=az


Try it Online

# Jolf, 10 bytes

ZlZd~Bx©{2


Try it here!

## Explanation

ZlZd~Bx©{2
~B     all numbers satisfying
©{  the prime condition ("the prime directive"?)
x    below x
Zd       (the differences between indices)
Zl       2 count the number of 2's


# Ruby, 43 + 8 (-rprime flag) = 51 bytes

->n{Prime.each(n-1).count{|i|(i-2).prime?}}


# Perl 6,  54  53 bytes

{2*(3..$_).rotor(3=>-1).grep: {all .[0,2]».is-prime}} {2*(3,5...$_).rotor(2=>-1).grep: {all $_».is-prime}} ### Explanation: { 2 * (3,5...$_)        # odd numbers
.rotor( 2 => -1 ) # grab 2 then backup one, repeat
.grep:            # find all that match the following
{
# create a Junction object of the following
all

# call .is-prime on both elements of the
# list given to this inner block
\$_».is-prime
}
}