malikov_a's blog

By malikov_a, history, 18 months ago, In English

When I run the program on my PC, it gives me the correct answer and everything goes okay. But when I submit that code here, it says that it gives the wrong answer. I copied exactly the same input as it is given in the test case and I get the correct answer, but only on the compiler installed on my PC (or on the online compiler of C++). I tried to rewrite it 20 times — no result. Chose another version of the language — no result. Is it possible that the compiler of codeforces glitches and starts giving the wrong result no matter what? P.s. My code passes first test case, but bugs on second one. P.p.s. Problem's number is 978C

  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
18 months ago, # |
  Vote: I like it +8 Vote: I do not like it

1) C++ 2) Ok on local 3) Not Ok on Codeforces

Put it together and you got some undefined behaviour in your code. Always. CF's compiler have no glitches.

»
18 months ago, # |
  Vote: I like it 0 Vote: I do not like it

You're using unsigned long, which is only 32 bits, to store numbers up to $$$10^{10}$$$, which may require more than 32 bits. You need to use a 64-bit type like long long instead.

  • »
    »
    18 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    First of all, thank you for advise. Second of all, I'm pretty convinced that wrong answer is not because of this. But I'll try to experiment with it, as soon as I'll have free time. Thank you, one more time.

    • »
      »
      »
      18 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      How are you so convinced? I literally changed all your unsigned long into long long and it passed test 2. It failed in test 4, but that's likely because your approach has some flaws. However, your concern about different results between Codeforces and your machine (which strongly suggests there is some undefined behavior involved) is almost certainly due to the use of unsigned long instead of long long.

    • »
      »
      »
      18 months ago, # ^ |
        Vote: I like it +3 Vote: I do not like it

      Easy experiment #1:

      unsigned long n;
      cin >> n;
      cout << n;
      

      Run this on both your local compiler and on CF's Custom Invocations with input 10000000000

      My guess that on your local it would print correct, in CF — not.

      Easy experiment #2:

      cout << sizeof(unsigned long);
      

      Run this on both local and CF.

      My guess: 8 on your local and 4 on CF.
      Meaning: unsigned long on your local is 64-bit type, on CF — 32-bit.

      Is it glitch? No, C++ doesn't say almost anything about size of primitive integer types. So size of unsigned long is implementation defined.

      Use this to be 100% sure about size of variable, or use long long/int from assumption, that almost everywhere first is 64-bit, second is 32-bit.