title: Python vs CPP: Why is the difference in speed so huge?
body: <pre class="lang-py prettyprint-override"><code>def main():
      i = 2
      sum = 1
      while i &lt; 100000:
          j = 2
          while j &lt; i:
              if i%j == 0:
                  sum += 1
                  break
              j += 1
          i += 1
  
      print(sum)
  
  
  if __name__ == "__main__":
      main()
  </code></pre>
  
  <pre class="lang-cpp prettyprint-override"><code>#include&lt;iostream&gt;
  
  using namespace std;
  
  int main() {
      int sum = 1;
      for (int i=2; i&lt;100000; i++) {
          for (int j=2; j&lt;i; j++) {
              if (i%j == 0) {
                  sum++;
                  break;
              }
          }
      }
      cout &lt;&lt; sum &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <h2><strong>C++</strong></h2>
  
  <p>Run with: <code>g++ -std=c++11 x.cpp -o x &amp;&amp; time ./x</code></p>
  
  <p>Time: <code>./x  1.36s user 0.00s system 99% cpu 1.376 total</code></p>
  
  <h2><strong>Python</strong></h2>
  
  <p>Run with: <code>python x.py</code></p>
  
  <p>Time: <code>python x.py  32.10s user 0.21s system 98% cpu 32.854 total</code></p>
  
  <p>Can anyone explain the huge difference between the time taken by the 2 programs? And what can be done to speed up the python one?</p>