Python中处理大数的问题

2024-06-16 18:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在解决一个关于codeforces的问题:-Here is the Question

我编写了python代码来解决同样的问题:-

n=int(input())
print(0 if ((n*(n+1))/2)%2==0 else 1)

但是对于测试用例1999999997See Submission-[TestCase-6]它失败了

尽管Python可以有效地处理大量数据,但为何失败?[See this Thread]


同样,当我在CPP[See Submission Here]中对其进行编码时,类似的逻辑也完美地工作了:-

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin>>n;
    long long int sum=1ll*(n*(n+1))/2;
    if(sum%2==0) cout<<0;
    else cout<<1;
return 0;
}

Tags: the代码submissioninputifhereiselse
2条回答

根据@juanpa.arrivillaga的见解进行了测试,这是一个很棒的兔子洞:

number = 1999999997

temp = n * (n+1)
# type(temp) is int, n is 3999999990000000006. We can clearly see that after dividing by 2 we should get an odd number, and therefore output 1

divided = temp / 2
# type(divided) is float. Printing divided for me gives 1.999999995e+18
# divided % 2 is 0

divided_int = temp // 2
# type(divided_int) is int. Printing divided for me gives 1999999995000000003

//强制整数除法,并始终返回整数:7//2将等于3,而不是3.5

根据您链接的另一个答案,python中的int类型可以处理非常大的数字

Float也可以处理大量的数字,但是在跨语言表示Float的能力方面存在一些问题。问题的关键在于并不是所有的浮动都能被准确捕获:在许多情况下,1.9999999 5e+18和1.9999999 5000000003e+18之间的差异非常微小,这无关紧要,但这是一个可以准确捕获的情况,因为您非常关心数字的最后一位

您可以通过观看此video了解更多信息

正如@juanpa.arrivillaga和@DarrylG在评论中提到的那样,我应该为整数除法使用floor操作符//,异常是由/除法操作符的浮点除法引起的

因此,正确的代码应为:-

n=int(input())
print(0 if (n*(n+1)//2)%2==0 else 1)

相关问题 更多 >