I was trying to write a solution for Problem 12 (Project Euler) in Python. The solution was just too slow, so I tried checking up other people's solution on the internet. I found this code written in C++ which does virtually the same exact thing as my python code, with just a few insignificant differences.
Python:
def find_number_of_divisiors(n): if n == 1: return 1 div = 2 # 1 and the number itself for i in range(2, n/2 + 1): if (n % i) == 0: div += 1 return div def tri_nums(): n = 1 t = 1 while 1: yield t n += 1 t += n t = tri_nums() m = 0 for n in t: d = find_number_of_divisiors(n) if m < d: print n, ' has ', d, ' divisors.' m = d if m == 320: exit(0) C++:
#include <iostream> int main(int argc, char *argv[]) { unsigned int iteration = 1; unsigned int triangle_number = 0; unsigned int divisor_count = 0; unsigned int current_max_divisor_count = 0; while (true) { triangle_number += iteration; divisor_count = 0; for (int x = 2; x <= triangle_number / 2; x ++) { if (triangle_number % x == 0) { divisor_count++; } } if (divisor_count > current_max_divisor_count) { current_max_divisor_count = divisor_count; std::cout << triangle_number << " has " << divisor_count << " divisors." << std::endl; } if (divisor_count == 318) { exit(0); } iteration++; } return 0; } The python code takes 1 minute and 25.83 seconds on my machine to execute. While the C++ code takes around 4.628 seconds. Its like 18x faster. I had expected the C++ code to be faster but not by this great margin and that too just for a simple solution which consists of just 2 loops and a bunch of increments and mods.
Although I would appreciate answers on how to solve this problem, the main question I want to ask is Why is C++ code so much faster? Am I using/doing something wrongly in python?
Replacing range with xrange:
After replacing range with xrange the python code takes around 1 minute 11.48 seconds to execute. (Around 1.2x faster)
xrangeinstead ofrange. Also just consider using C++