The following is my answer to Project Euler's third problem. Here's the python implementation:
def isPrime(n):
for i in range(n/2)[3::2]:
if n % i == 0:
return False
return True
def largestPrime(n):
for i in range(3, n/2):
if n % i == 0 and isPrime(n/i):
return n/i
return -1
largestPrime(600851475143)
And here's the same implementation rewritten in C++:
#include <iostream>
using namespace std;
bool isPrime(long n)
{
for(int i = 3; i < n/2; i+=2)
{
if(n % i == 0)
return false;
}
return true;
}
long largestPrime(long n)
{
for(int i = 2; i < n/2; i++)
{
if(n % i == 0 and isPrime(n/i))
return n/i;
}
return -1;
}
int main()
{
cout << largestPrime(600851475143) << endl;
return 0;
}
When I run the C++ code, it computes the correct answer (6857) within seconds. But when I run the python code, it seems to go on forever. What's is it that python performance is so poor here?