Why is my code giving different answers on Online Judge and locally?

4223 views c++
2

I'm fairly new to competitive programming and I've ran into this problem a couple of times already in CodeForces and I'm not really sure what's happening.

The thing is that when I run this code (example from http://codeforces.com/contest/1041/problem/B):

#include <iostream>

long gcd (long n1, long n2) {
    return (n2 == 0) ? n1 : gcd (n2, n1 % n2);
}

long min(long a, long b){
  return a < b ? a : b;
}

int main(){
  std::ios_base::sync_with_stdio(false);

  long a, b, x, y;

  std::cin >> a >> b >> x >> y;

  long g = gcd(x, y);

  std::cout << min(a / (x / g), b / (y / g)) << std::endl;

With the input of (4th input of the problem in the codeforces page)

1000000000000000000 1000000000000000000 999999866000004473 999999822000007597

Locally I get the right answer which is

1000000063

But when I send it to CodeForces, it gives me "Wrong Answer" and when I go check what answer it got, it says

0

To check if it was something I'm doing wrong with my code or not, I coded the same thing in Java and it worked just fine.

So I checked if it was something to do with the version I was sending it as (C++17) sending in a different version (C++11), but got "Wrong Answer" again but with the answer

1

So I'd like to know what I'm doing wrong with my C++ code that it doesn't run as expected in the Online Judge.

PS. I tried running it on valgrind but I didn't seem to get any warnings as well.

answered question

long might be 4-bytes on CF while 8-bytes on your machine. Try using long long which is practically 8-bytes everywhere.

Especially given the 'I coded it as Java' test I think @iBug is correct. In Java (and clearly on your system) long is 64 bits but it doesn't have to be. Try uint64_t for a guaranteed 64 bits

Get yourself an actual compiler and run your code. You have the code, you have the test case, what is stopping you from compiling and testing the code yourself, thus discovering that the issue may be overflow?

@PaulMcKenzie The OP said he did it locally. It's not quite easy to get another environment where long is 4-bytes.

1 Answer

1

It seems long on Codeforces is only 4 bytes and can store only upto 2,147,483,647 while it can store larger value (maybe 8 bytes) in your local environment.

You can add #include <cstdint> and use the type int64_t to use 8-byte signed integer with more compatibility.

posted this

Have an answer?

JD

Please login first before posting an answer.