c++integer-overflowceil

Printing answer directly using cout gives wrong answer, whereas storing the answer and then printing using cout get accepted


I am solving problem 1A : Theatre Square(https://codeforces.com/problemset/problem/1/A) on Codeforces.

Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.

What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.

Input : The input contains three positive integer numbers in the first line: n,  m and a (1 ≤  n, m, a ≤ 10^9).

Output : Write the needed number of flagstones.

The following code does not work, when I print the answer directly using cout:

#include <bits/stdc++.h>

using namespace std;

int main() {
    long long n, m, a;

    cin >> n >> m >> a;

    cout << (ceil(double(n) / a) * ceil(double(m) / a)) << endl;    
    return 0;
}

But works when I store the answer and then print it :

#include <bits/stdc++.h>

using namespace std;

int main(){
    long long n, m, a, number;

    cin >> n >> m >> a;

    number = (ceil(double(n) / a) * ceil(double(m) / a));    
    cout << number << endl;

    return 0;
}

Please help me understand why it gives wrong answer in the first case for the following input:

n = m = 10^9 ; a = 1

Solution

  • As noted, in the first case you are using std::ceil which returns a double and are printing that type of value. In the second case you are assigning that double value to a variable of type long long which is an integer type, and then printing that long long value.

    The two should not be expected to print the same.