0

I was trying to do some newbie competitive programming problems (because currently i am a newbie :D). I got this strange error with constant and long long division... And watched carefully about tipe conversion problems (can't see any).

I don't understand why such division, gives 1e18 instead of desired result...

#include <iostream>

#define ll long long
#define UPPER (ll)1e18 + 1

ll mult(ll first, ll second)
{
    ll div = UPPER / second;
    std::cout << UPPER / second << " " << UPPER << std::endl;
    if (first > div)
    {
        return UPPER;
    }

    return first * second;
}


int main()
{
    //51e10
    ll first = 510000000000, second = 510000000000;
    
    std::cout << mult(first, second);
}


And the output i get is:

1000000000000000000 1000000000000000001
908560695322214400
Flecart
  • 15
  • 1
  • 3
  • 5
    One more example of how stupid these "competitive programming" idiosyncraties are. Take a closer look at what your code looks like after `UPPER` has been substituted. Then ditch the insane macros, the [`std` namespace dump](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) and the [needless compiler-specific header](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). – Quentin Aug 02 '21 at 08:21
  • "duplicate" but in C: [The need for parentheses in macros](https://stackoverflow.com/q/10820340/995714). And never use `#define ll` to get long long. Use `int64_t` instead, or at least use `using` or `typedef` to redefine types – phuclv Aug 02 '21 at 08:31
  • [Confused by squaring macro SQR](https://stackoverflow.com/q/17071504/995714), [Macroprocessor in c++](https://stackoverflow.com/q/25873951/995714) – phuclv Aug 02 '21 at 08:39

2 Answers2

1

Macros are just simple text replacements. UPPER / second will be replaced with (ll)1e18 + 1 / second which is always equal to (ll)1e18 unless second is 1

You must use parentheses around that

#define UPPER ((ll)1e18 + 1)
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • Thank you! this solved my problem, the post can be closed now. – Flecart Aug 02 '21 at 08:35
  • @Flecart you may accept an answer as having solved your issue and close your question by ticking the checkmark under the voting buttons on the left of the answer. – Quentin Aug 02 '21 at 08:39
0

Why are you using long long? I think this datatype refers to an integer right? I think you expect out of the divison a floating point number. I would suggest to try your approach with long double (which has the same size like long long). Type long double is a floating point type that is larger than or equal to type double.

Chief
  • 149
  • 2
  • 11
  • no i don't i just needed a number under the first one. i needed to make a division for broader problem – Flecart Aug 02 '21 at 08:35