Partition an integer x into n primes: Difference between revisions

m
m (→‎{{header|Phix}}: is_prime() now builtin)
Line 1,075:
=={{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>}}
Fpartition[4035520, 34]</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}}
<pre>
Partitioned 4035518 with 32 primes: 5+7+4034313
Print["Partitioned ", x, "19 with ", n, "3 primes: ", 3+5+11
Partitioned 20 with 4 primes: impossible
</pre>