3

If

n=10;

Union[Flatten[Table[If[PrimeQ[p] == True && p + q == 2 n, {p, q}, {}], {p, 3, 
2 n}, {q, 1, 2 n - p}], 1]]

which its output is

{{}, {3, 17}, {5, 15}, {7, 13}, {11, 9}, {13, 7}, {17, 3}, {19, 1}}

I like to have

{{}, {3, 17}, {5, 15}, {7, 13}, {11, 9}, {19, 1}}

or

{{3, 17}, {5, 15}, {7, 13}, {11, 9}, {19, 1}}

as a result, i.e., since {3,17} is the same as {17,3}, we only need one of them.

Thanks!

Michael Seifert
  • 15,208
  • 31
  • 68
asad
  • 838
  • 4
  • 13

2 Answers2

6

Starting with

list = {{}, {3, 17}, {5, 15}, {7, 13}, {11, 9}, {13, 7}, {17, 3}, {19, 1}}

You can remove reordered sublists with

noDuplicates = DeleteDuplicatesBy[ list, Sort ]
{{}, {3, 17}, {5, 15}, {7, 13}, {11, 9}, {19, 1}}

Then you can remove empty sublists with

noEmpties = DeleteCases[ noDuplicates, {} ]
{{3, 17}, {5, 15}, {7, 13}, {11, 9}, {19, 1}}
jjc385
  • 3,473
  • 1
  • 17
  • 29
  • Thanks for your answer, but there is a small problem, My Mathematica version is 9, and DeleteDuplicatesBy is not defined. – asad Oct 31 '17 at 17:44
  • 2
    DeleteDuplicates[list, Equal @@ Sort /@ {##} &] in older versions. Id also suggest more simply DeleteDuplicates[Sort/@list] will be faster if you don't mind having everything sorted in the result. – george2079 Oct 31 '17 at 18:08
  • @george2079, thanks, it works! – asad Nov 01 '17 at 04:53
2
n=10;
Flatten[DeleteDuplicates[Table[If[PrimeQ[p] && p + q == 2 n, Sort[{p, q}], Nothing], {p, 3, 
2 n}, {q, 1, 2 n - p}]], 1]

{{3, 17}, {5, 15}, {7, 13}, {9, 11}, {1, 19}}

Update

Much faster if the duplicates and empty lists are avoided from the get go.

n = 10; 
Cases[IntegerPartitions[2 n, {2}], ls : {___, _?PrimeQ, ___} :> 
Switch[ls, {1 | 2, Except[_?PrimeQ]} | {Except[_?PrimeQ], 1 | 2}, Nothing, _, ls]]

{{19, 1}, {17, 3}, {15, 5}, {13, 7}, {11, 9}}

Comparison:

n = 1000;

l1 = Flatten[
DeleteDuplicates[
 Table[If[PrimeQ[p] && p + q == 2 n, Sort[{p, q}], Nothing], {p, 
   3, 2 n}, {q, 1, 2 n - p}]], 1]; // AbsoluteTiming

l2 = Cases[IntegerPartitions[2 n, {2}], 
ls : {___, _?PrimeQ, ___} :> 
 Switch[ls, {1 | 2, Except[_?PrimeQ]} | {Except[_?PrimeQ], 1 | 2},
   Nothing, _, ls]]; // AbsoluteTiming

Equal @@ (Length /@ {l1, l2}) && Complement[Sort /@ l1, Sort /@ l2] == {}

{1.58086, Null}

{0.004746, Null}

True

Suba Thomas
  • 8,716
  • 1
  • 17
  • 32