I want to put in $n$ and get the possible factorizations into prime powers. Let's say for 24 I want {{8,3}, {4,2,3}, {2,2,2,3}}.
The algorithm for doing this on paper is this:
- Find the prime factorization of $n$. Example case: $24=2^3 \cdot 3$
- Take powers and find their partitions. Example case: $3=2+1=1+1+1$ and $1$.
- Construct the different factorizations of $n$. Example case: $24=8\cdot3=4\cdot2\cdot3=2\cdot2\cdot2\cdot3$.
My code is this:
primeFactorsWithPowers = FactorInteger[n];
primeFactorsWithPartitionedPowers = {#[[1]], IntegerPartitions[#[[2]]]} & /@ primeFactorsWithPowers;
primePowerFactors = #[[1]]^#[[2]] & /@ primeFactorsWithPartitionedPowers;
factorizationsIntoPrimePowersRaw = Tuples@primePowerFactors;
factorizationsIntoPrimePowers = Flatten /@ factorizationsIntoPrimePowersRaw
For n = 360 this gives {{8, 9, 5}, {8, 3, 3, 5}, {4, 2, 9, 5}, {4, 2, 3, 3, 5}, {2, 2, 2, 9, 5}, {2, 2, 2, 3, 3, 5}} which is correct. But it seems a bit long and clumsy to have so many obscure operations for this. Being a badass I attempt to wrap it all in a function:
primePowerFactorizations[n_] := Map[Flatten, #[[1]]^#[[2]] & /@ Map[{#[[1]], IntegerPartitions[#[[2]]]} &, FactorInteger[n]] //Tuples]
or maybe:
primePowerFactorizations[n_] :=
Map[Flatten,
Tuples[
#[[1]]^#[[2]] & /@
Map[{#[[1]], IntegerPartitions[#[[2]]]} &,
FactorInteger[n]]]]
Either way it looks like something that I will never be able to read again. Can I write this in a nicer way? Maybe you know of a method or function that allows to shorten this?
I don't understand how multiple uses of /@, @, // are supposed to work. For me a nice way to see the order of operations (and unwrap it with my eyes) would seem if I could write it like this:
primePowerFactorizations[n_] :=
Flatten /@
Tuples @
#[[1]]^#[[2]] & /@
{ #[[1]], IntegerPartitions[#[[2]]] } & /@
FactorInteger[n]
But this doesn't work at all.
Either way it looks like something that I will never be able to read againWell, welcome to programming in Mathemtica :) I once spend one hr trying to understand few lines of code in Mathematia book written by one of the experts in Mathematica. I could not figure how the code works. So I gave up. To make code easier to understand, I would break it in pieces. do not tail-call too many functions. I would keep the limit to 2 calls and at most 3. So instead off1[f2[f3[f4[x]]]]you would writey=f4[x]andy=f3[y]andy=f2[y]and so it. you get the idea. – Nasser Mar 24 '17 at 02:08Module[]and other scoping constructs; see this for some guidance. – J. M.'s missing motivation Mar 24 '17 at 07:40