簡體   English   中英

C ++和python中的算法相同,但輸出不同

[英]Same algorithm in c++ and python but different output

C ++

#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
unsigned long long int t,n,i,m,su,s,k;
int main()
{
        cin>>n;
        if(n==0)
        {
            cout<<"0\n";
            return 0;
        }
        m = sqrt(n);
        su = m*(m+1)/2;
        s = n-1;
        for(i=2;i*i<=n;i++)
        {
            k = n/i;
            s = s + (k-1)*i + k*(k+1)/2 - su;
        }
        cout<<s<<"\n";
}

蟒蛇

import math
n = int(input())
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<=n:
        k = int(n/i)
        s = s + ((k-1)*i) + int(k*(k+1)/2) - su
        i = i+1
    print(s)

答案不同1000000000
對於C ++代碼輸出= 322467033612360628
對於python代碼輸出= 322467033612360629
為什么答案不同? 我不認為這是C ++整數溢出引起的,因為在64位環境中,無符號long long int范圍為18,446,744,073,709,551,615

編輯:刪除了造成混亂的變量

這與Python 3與Python 2中除法運算符變化有關。

在Python 2中,如果分子和分母都是整數,則/是整數下位除法:

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.
>>> 2/3
0
>>> 2.0/3.0
0.6666666666666666
>>> 
>>> 1/2 == 1.0 / 2.0
False

請注意,在Python 2中,如果分子或分母都是浮點數,則結果將是浮點數。

但是Python 3將/更改為'True Division',並且您需要使用//來獲得整數底除:

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.
>>> 2/3
0.6666666666666666
>>> 2//3
0
>>> 1/2 == 1.0/2.0
True
>>> 1//2 == 1.0/2.0
False

C ++在整數之間使用地板除法:

int main()
{
    int n=2;
    int d=3;
    cout<<n/d;    // 0
}

如果我運行以下代碼(改編自您的代碼):

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<=n:
        k = int(n/i)
        s = s + ((k-1)*i) + int(k*(k+1)/2) - su
        i = i+1
    print(s)

在Python 3下,我得到:

322467033612360629

在Python 2下,我得到:

322467033612360628

如果更改此行:

s = s + ((k-1)*i) + int(k*(k+1)/2) - su

s = s + ((k-1)*i) + int(k*(k+1)//2) - su # Note the '//'

它將解決Python 3下的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM