Hi guys and guysettes,
The little Mathematica I've been using/seen so far, it seems to be all about neat "one-liners" using the underlying functions and working with lists & maps to solve issues, and very little looping and down and dirty coding.
So, when I attempt to do something like this, I get extremely inefficient code (yes, I'm relying on one explicit loop, though): (The task is to find the lowest value that is evenly divisible by 1 through 20)
results = {1}; i = 0;
While[Total[results] != 0,
i++;
results = Mod[i, #] & /@ Range[1, 20];
]
i
..which takes about 8000 seconds to complete. Had I used another language, I would naturally had an inner-loop that breaks after the first "failing" 'Mod', but here I tried to use what I thought to be more of a "Mathematica way" and the results are horrible. So, I'm asking for advice on how you would construct a brute-force way of dealing with this?
For comparison, creating a similar way to solve the problem in Python, I got it to complete in about 1000 Seconds. Creating an "early-exit" solution without using unecessary lists for results, (the way I would normally code), it got down to 120 seconds.
LCM @@ Range[20]
$\endgroup$Solve[i \[Element] Integers && And @@ (Mod[i, #] == 0 & /@ Range[20]), i]
finds the answer of 232792560 in essentially no measurable time. $\endgroup$Solve
is not a general solution either but it can quite often find an approach better than brute force (given a well-posed problem), so is at least somewhat generalizable. $\endgroup$FactorInteger[]
there... $\endgroup$