While I submitted, my solution was accepted but now I check next day to know my ranking it shows that in last test case no output is printed. I tried same code with that input on my laptop and it works fine. Can someone point the mistake?
Error: "wrong output format Unexpected end of file — token expected"
Code:
#include <stdio.h>
int main(){ // commented section removed
int i, j, k;
long int n;
scanf("%ld", &n);
long int sum = 0;
sum = n*(n+1)/2;
if(sum%2 == 1) printf("1");
if(sum%2 == 0) printf("0");
return 0;
}
The long int is not enough as when n is 1e9, the sum can be 1e18. Try using long long and you can get AC :).
The bug is in this 4 lines of your code:
Or more specifically, this line:
sum = n*(n+1)/2;
Since typelong int
holds a maximum value of2147483647
, when n reaches999999998
(as in test #10),sum
equals to499999998500000001
, which is way larger than what it can hold. Note thatn
does not overflow, but we still have to change it tolong long int
to not get integer overflow in the linesum = n*(n+1)/2;
To fix this, change to:Bingo!
Good details!
Thanks for the details, but I don't get why "n" should also be long long int type? I agree with you that sum should have been long long int. Can't we manage with "n" being long int only? If you happen to know the details as to how "sum = n*(n+1)/2" happens to execute which probably makes you say that "n" should be long long int then please share. Anyhow, thanks for the reason :)
If n is a 32-bit integer, then the multiplication will be carried out in 32-bits, then cast to 64 bits. You'd want something like
long long sum = 1LL * n * (n + 1) / 2
to avoid overflow.