Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is related to the <a href="http://www.python.org/dev/peps/pep-0238/" rel="nofollow">change in the division operator</a> in Python 3 vs Python 2. </p> <p>In Python 2, the <code>/</code> is integer floor division if both numerator and denominator are integers:</p> <pre><code>Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; 2/3 0 &gt;&gt;&gt; 2.0/3.0 0.6666666666666666 &gt;&gt;&gt; &gt;&gt;&gt; 1/2 == 1.0 / 2.0 False </code></pre> <p>Notice that in Python 2, if either numerator or denominator are floats, the result will be a float. </p> <p>But Python 3 changes the <code>/</code> to be 'True Division' and you need to use <code>//</code> to get integer floor division:</p> <pre><code>Python 3.3.2 (default, May 21 2013, 11:50:47) [GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; 2/3 0.6666666666666666 &gt;&gt;&gt; 2//3 0 &gt;&gt;&gt; 1/2 == 1.0/2.0 True &gt;&gt;&gt; 1//2 == 1.0/2.0 False </code></pre> <p>C++ uses floor division between integers:</p> <pre><code>int main() { int n=2; int d=3; cout&lt;&lt;n/d; // 0 } </code></pre> <p>If I run this code (adapted from yours):</p> <pre><code>from __future__ import print_function import math n = 1000000000 if n==0: print('0') else: m = int(math.sqrt(n)) su = int(m*(m+1)/2) s = n-1 i=2 while i*i&lt;=n: k = int(n/i) s = s + ((k-1)*i) + int(k*(k+1)/2) - su i = i+1 print(s) </code></pre> <p>Under Python 3 I get:</p> <pre><code>322467033612360629 </code></pre> <p>Under Python 2 I get:</p> <pre><code>322467033612360628 </code></pre> <p>If you change this line:</p> <p><code>s = s + ((k-1)*i) + int(k*(k+1)/2) - su</code> </p> <p>to </p> <p><code>s = s + ((k-1)*i) + int(k*(k+1)//2) - su # Note the '//'</code></p> <p>it will fix the problem under Python 3</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload