hmir
hmir

Reputation: 1413

Python Code is Way Slower Than The Same C++ Code?

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?

Upvotes: 0

Views: 225

Answers (3)

Th3T3ch13
Th3T3ch13

Reputation: 1

Python is, as previously mentioned, a interpreted language, but another drawback is you are more than likely running it through an IDE such as IDLE or IDLE3. These are made With Python and can take up more cpu usage than a compiled language, such as C++. I hope this helped in any way in your favor. ~Th3T3ch13

Upvotes: 0

Amadan
Amadan

Reputation: 198314

A) Python is interpreted, C is compiled. The latter class is almost always faster than the former.

B) isPrime is executed a number of times. In it, you have range(n/2)[3::2], which will construct (a rather large) array many times. In contrast, your C code only has a simple loop, without memory allocation and initialisation.

C) Tony D's question comment might well have merit. Check your long size.

Upvotes: 2

Cuban Pete
Cuban Pete

Reputation: 111

Its because Python is an interpreted language while C++ is a compiled language.

See this stack overflow question for a more in-depth description of the differences between the two. Note that this touches the surface of it.

Compiled vs. Interpreted Languages

Also refer to this page on the Python site for brief descriptions of Python compared to other programming languages.

https://www.python.org/doc/essays/comparisons/

Upvotes: 2

Related Questions