vjindal23's blog

By vjindal23, history, 5 years ago, In English

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;
}
  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
Rev. 7   Vote: I like it +5 Vote: I do not like it

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 :).

»
5 years ago, # |
  Vote: I like it +4 Vote: I do not like it

The bug is in this 4 lines of your code:

long int n;
scanf("%ld", &n);
long int sum = 0;
sum = n*(n+1)/2;

Or more specifically, this line: sum = n*(n+1)/2; Since type long int holds a maximum value of 2147483647, when n reaches 999999998 (as in test #10), sum equals to 499999998500000001, which is way larger than what it can hold. Note that n does not overflow, but we still have to change it to long long int to not get integer overflow in the line sum = n*(n+1)/2; To fix this, change to:

long long int n;
scanf("%lld", &n);
long long int sum = 0;
sum = n*(n+1)/2;

Bingo!

  • »
    »
    5 years ago, # ^ |
      Vote: I like it +4 Vote: I do not like it

    Good details!

  • »
    »
    5 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    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 :)

    • »
      »
      »
      5 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      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.