Number of ways to sum [1..n] with [n+1..2n] such that each sum is prime

CJam, 38 35 32 bytes

0{)_e!{ee{1b1$+)_m!)\)%},!},,p}h

This is an infinite list version. If you run it using the Java compiler, you will keep on getting result for increasing n on each line until the program crashes (if it does. Did not test).

For sanity, run the finite version using this link. You can change the number in the input to see a longer list.

How it works:

0{                            }h  e# This acts as an infinite do-while loop here
  )_                              e# Starting from 0, increment the number and copy it
                                  e# Lets call this number at each iteration as N
    e!                            e# Get all possible permutations of the array 0..N-1
      {                   },      e# Filter the list of permutations based on this code block
       ee                         e# Convert the permutation array into an [index value]
                                  e# pair array. For ex. [5 2]ee gives [[0 5] [1 2]]
         {             },         e# Pass each index value pair through this filter
          1b1$+)                  e# Sum the index and value and add current N + 1 to it
                                  e# At this point, we have something equivalent to
                                  e# pairwise addition of [1 .. n] and [n .. 2n - 1]
                _m!)\)%           e# Now we do ((N - 1)! + 1)%N to see if N is prime
                                  e# This is Wilson's theorem and will give 0 for primes
                         !        e# Now we have a filtered index-value pairs which all
                                  e# correspond to non-prime numbers. If the list is empty,
                                  e# Then all numbers are prime. Thus we do a ! on empty list
                                  e# to get truthy.
                            ,p    e# Take the total permutations where X + pN(Y) are all
                                  e# primes and print the number to STDOUT immediately
                                  e# We are left with the initial incremented N on stack
                                  e# which is always non-zero, so the loop continues
                                  e# infinitely 

UPDATE: 2 bytes saved, thanks to Martin!


Pyth - 35 32 27 bytes

The obvious approach. The while loop logic is taking a lot of bytes. Thanks to @Jakube for telling me about .V and saving a lot of bytes. Explanation coming soon.

.V1lf!sm%[email protected]

Try first n here online


Python 2, 147 bytes

from itertools import*
n=1;R=range
while n:print sum(all(x%d for x in map(sum,zip(R(n),c))for d in R(2,x))for c in permutations(R(n+2,2*n+2)));n+=1

The import itertools rule of thumb tells me there's probably a better way...

A few bytes are saved by summing [0 ... n-1] with [n+2 ... 2n+1] instead.