1

I was solving a problem on codeforces:- Here is the Question

I wrote python code to solve the same:-

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

But it failed for the test-case: 1999999997 See Submission-[TestCase-6]

Why it failed despite Python can handle large numbers effectively ? [See this Thread]


Also the similar logic worked flawlessly when I coded it in 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;
}
sophros
  • 14,672
  • 11
  • 46
  • 75
Tanmay Harsh
  • 63
  • 1
  • 7
  • 2
    You are using `float` objects, which will be the result of using the `/` operator – juanpa.arrivillaga Apr 20 '21 at 12:05
  • 3
    In Python use integer division operator i.e. `//` rather than float division `/`. C is different in that integer division is performed with integer arguments. – DarrylG Apr 20 '21 at 12:07
  • Yes, I just missed out that...Thankyou all ! – Tanmay Harsh Apr 20 '21 at 12:16
  • 1
    [python floating point issue and limitations](https://docs.python.org/3/tutorial/floatingpoint.html#) – sahasrara62 Apr 20 '21 at 12:50
  • @DarrylG in Python 2.7 and earlier, division between integers worked the same as it does in C. Python 3.0 changed it because they felt too many people were getting confused. It just proves that you can't win. – Mark Ransom Apr 20 '21 at 15:19

2 Answers2

2

Ran a test based on the insight from @juanpa.arrivillaga and this has been a great rabbit hole:

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

// Forces integer division, and will always return an integer: 7 // 2 will be equal to 3, not 3.5

As per the other answer you have linked, the int type in python can handle very large numbers.

Float can also handle large numbers, but there are issues with our ability to represent floats across languages. The crux of it is that not all floats can be captured accurately: In many scenarios the difference between 1.999999995e+18 and 1.999999995000000003e+18 is so minute it won't matter, but this is a scenario where it does, as you care a lot about the final digit of the number.

You can learn more about this by watching this video

m.oulmakki
  • 296
  • 1
  • 6
1

As mentioned by @juanpa.arrivillaga and @DarrylG in comments, I should have used floor operator// for integer division, the anomaly was cause due to float division by / division operator.

So, the correct code should be:-

n=int(input())
print(0 if (n*(n+1)//2)%2==0 else 1)
Tanmay Harsh
  • 63
  • 1
  • 7