Since I'm fairly new to Mathematica, I'm trying to learn better ways to improve my coding skills so I've turned to Project Euler and this site to speed up my learning pace. Anyways, I was trying to solve problem 32 on the project Euler forum and came up with the following code
PanDigital[n_, m_] := Sort[Flatten[IntegerDigits /@ {n, m, n m}]] == Range[9];
Module[{k}, k = Select[Flatten[Table[{i j, PanDigital[i, j]}, {i, 2, 9}, {j, 1234,
9876}] ~Join~ Table[{i j, PanDigital[i, j]}, {i, 12, 98}, {j, 123, 987}],
1], #[[2]] == True &]; k = Union@Select[Flatten[k], IntegerQ] // Total] // Timing
{2.620817, 45228}
By the way here is the question:
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
My question is, how can I make this code better, in terms of style and speed. I imagine using things like Reap
and Sow
could improve the readability and also speed. Also while my code run in under 3 seconds, I saw other people claiming less than 10 milliseconds time. Of course, using ParallelTable
decreased the time to about 0.6 seconds on my PC but this is still not comparable to those times. Any advise is greatly appreciated.