Python中处理大数的问题

问题描述

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

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

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

但是对于测试用例失败了:1999999997 See 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;
}

解决方法

根据@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 类型可以处理非常大的数字。

浮点数也可以处理大数,但我们在跨语言表示浮点数的能力方面存在问题。关键是并不是所有的浮点数都可以准确捕获:在许多场景中,1.999999995e+18 和 1.999999995000000003e+18 之间的差异是如此微小,这无关紧要,但这是一个场景它在哪里,因为您非常关心数字的最后一位。

您可以通过观看此video

了解更多信息 ,

正如@juanpa.arrivillaga 和@DarrylG 在评论中提到的,我应该使用 floor operator// 进行整数除法,异常是由于通过/除法运算符浮动除法

所以,正确的代码应该是:-

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