Partition an integer x into n primes: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: is_prime() now builtin)
Line 1,075: Line 1,075:
=={{header|Mathematica}}==
=={{header|Mathematica}}==


This can be done with IntegerPartitions:
{{output?|Mathematica}}
<lang Mathematica>partition[x_,n_]:= "Partitioned "<>ToString[x]<>" with "<>ToString[n]<>" primes: "<>StringRiffle[
ToString/@First[Sort[Sort/@Select[IntegerPartitions[x,{n},Prime/@Range[PrimePi[x]]],Length[Union[#]]===n&]],{"impossible"}]
,"+"]


partition[18, 2]
{{incorrect|Mathematica| <br><br> the partitioning of &nbsp; '''40,356''' &nbsp; into three primes isn't the lowest primes that are possible, <br>
partition[19, 3]
the primes should be: <br><br> &nbsp; <big> '''3''', &nbsp; '''139''', &nbsp; '''40213'''. </big> &nbsp; <br>}}
partition[20, 4]</lang>


Just call the function F[X,N]
<lang Mathematica>F[x_, n_] :=
Print["Partitioned ", x, " with ", n, " primes: ",
StringRiffle[
ToString /@
Reverse[First@
Sort[Select[IntegerPartitions[x, {n}, Prime@Range@PrimePi@x],
Length@Union@# == n &], Last]], "+"]]

F[40355, 3]</lang>




{{out}}
{{out}}
<pre>
<pre>
Partitioned 40355 with 3 primes: 5+7+40343
Partitioned 18 with 2 primes: 5+13
Partitioned 19 with 3 primes: 3+5+11
Partitioned 20 with 4 primes: impossible
</pre>
</pre>