Originally published at warrenwong.org.
While trying to become more Pythonic in my coding, I have been going over some of my Project Euler toy problems. It's mostly fun and cathartic, but I did notice something fairly interesting.
On problem 7 of Project Euler, the solution seems fairly simple to implement. My implementation for both is rather similar (no real obvious way to make it utilize some of the newer features of JavaScript or Python 3 that I can see). My assumptions was that it would take about the same amount of time to run.
NodeJS implementation:
const isPrime = n => {
for (let i = 2; i < n; i++) {
if (n % i === 0) {
return false;
}
}
return true;
};
const getPrime = n => {
let count = 0;
let num = 2;
while (n > count) {
if (isPrime(num)) {
count += 1;
}
num += 1;
}
return num - 1;
};
Python implementation:
def is_prime(n):
for i in range(2, n):
if (n % i == 0):
return False
return True
def get_prime(n):
count = 0
num = 2
while n > count:
if is_prime(num):
count += 1
num += 1
return num - 1
I mean, it's fairly simple and straight-forward. The time complexity of both should be exactly the same, but I couldn't believe the difference. I ran it several times with the Unix time
utility and I consistently got sub 2 seconds for the NodeJS implementation and over 25 seconds for Python 3.
It's actually incredibly alarming for me to see the difference since I would think the performance would be fairly similar. Since I was curious, seems like other more "formal" benchmarks also confirm this.
Well color me surprised.
Top comments (4)
I also get similar results on my system.
Just for fun I copied your algorithm into Rust to compare!
Results
Some languages have better performance in certain areas. NodeJS in particular has beaten many languages calculating numbers.
NodeJS is simply one of if not the best scripting languages AFAIK for calculating numbers really fast.
But I have to admit, the Python implementation is just pleasing to read while I am straining my eyes with the NodeJS one.
Yea, I agree, especially on this specific example.