Before anyone starts in, I know that talking about "speed" in a programming language isn't always the most... useful discussion. That said, speed is the issue here.
I tackled Project Euler problem 5 in both languages and, while my implementations in both languages look fairly similar to my eye, the runtime is vastly different. Java returns an answer in only a few seconds whereas Python can take up to a minute (on the same machine, of course). I'm quite certain this is less the fault of Python and more the fault of a programmer (me) who hasn't quite learned to think Pythonically.
Note that I am not asking you to rewrite my code. I'm simply looking for a few nudges in the right direction. (And yes, I've looked at some similar threads but most of those are over my head and aren't directly comparing the same algorithm in two languages. This thread is helpful, but again, doesn't directly compare Java and Python - and frankly the answers are a little hard to follow.)
Without further ado:
Java
public class Problem5 {
public static void main(String[] args){
boolean found = false;
for (int i = 20; !found; i += 20){
if (DivisThrough20(i)) {
found = true;
System.out.println(i);
}
}
}
private static boolean DivisThrough20(int number){
boolean result = true;
for (int i = 19; result && i > 1; i--){
if (number % i != 0) result = false;
}
return result;
}
}
Python
def DivisThroughTwenty(number):
for x in range(20,1,-1):
if number % x != 0:
return False
return True
# the number we're looking for can't be any lower than 20, so we'll
# start there as a small optimization
testNumber = 20
keepLooking = True
while keepLooking:
if not DivisThroughTwenty(testNumber):
testNumber += 20
else:
keepLooking = False
print testNumber
It's funny, reading these side by side I can already see that the Python version of this algorithm is slightly more optimized than the Java version, yet it's still much slower. I'm even more curious to find another way to approach the problem now.