 # Multiplying two int's to get a long long

Can someone please tell me how to multiply two numbers whose product is long long int. I tried it using
ll x = (ll)(a*b) where a and b are integers (say 10000000) so the answer should be 1e14. Right? But compilers are giving overflow (code compile and run). Even while writing this question i feel weird whether it is to be asked or not because this is kind of a strange one (may be silly). Someone please Help.
Question is http://codeforces.com/contest/834/problem/C and my solution is http://codeforces.com/contest/834/my

`ll x = (ll)a * b;`
Here `a` is being explicitly converted to `ll` type, so the other values in the expression will also be converted to `ll` (unless there is a `double`) before evaluation. Check out type conversion.

By the way the link http://codeforces.com/contest/834/my is attempting to show me my submissions 3 Likes

Some compilers need explicit uses.
So, if I have two ints the compiler will try to fit the result in an integer size variable only. But since result is large, you will get overflow, even though you are trying to store it in a long long variable.

So what you could do is put a 1LL in the beginning. For example, two multiply two ints and storing it in a long long as follows:

long long n = 1LL * x *y

2 Likes

@vishesh_345
(ll)(ab) is different from (ll)ab

Sorry I was not aware of it (was silly xD). I did (ll)(a*b). So shouldn’t be the whole product be typecasted to long long. Have I got something wrong.
Here is my solution https://ideone.com/143ZiS

Thanks @sun_d it worked.

Nope. As @sun_d said, if you operate on 2 `int`s the compiler will fit the result in an `int` even if overflow occurs.

Yes @meoow Thank you. Got it now. Just one thing to note here if you’re using this method, “`1LL * x * y`” will work but “`x * y * 1LL`” will not, because the operator associativity of multiplication is from left to right . Hence you have to be careful to always put `1LL` at the front (or second place).

Worth Noticing.

long long x = (int )a * 1ll * (int )b;

ll or LL converts the integer to long long.

let’s suppose, int a = 1; now if you do a << 40 it will overflow and you’ll see the undefined behavior.

a*1ll << 40 will work fine because ‘a’ now would be behaving like a long long.

This method is used to avoid the overflow. If the product of a and b happens to cross integer limit (and none of a and b are of type long long) then the product would overflow even though you have defined LHS as long long.

Go to this link or this will give you a better insight about LL.

Hope this helps

1 Like

I am seeing this thing is giving shocks to many people I think its the third (or fifth?) time i am seeing this Q in same month I forgot to have a look at the previous questions. Sorry for that. I never came across this thing before (i wonder how). You can close this question now. I have got my mistake. Thanks to all again.

1 Like
//