overflowof int

if i take 'i as int and num is long long and go like this
 
num=i*i;

then it will show TLE.
but it works fine if i go like this
1
2
num=i;
num*=i;


that means that in i*i case the value of i*i is stored as int datatype?
while in 2nd case it is stored in num itself which is long long right?

why i am getting TLE rather than some sort of exception or error if its overflowing or i am missing something?
is that means i*i ways takes more computation as compared to the 2nd method?
Last edited on
that means that in i*i case the value of i*i is stored as int datatype?


Yes. The compiler will evaluate the * before the =. Since 'num' has nothing to do with the *, the compiler doesn't know that the result of the * is supposed to be a long long. Since the * only involves ints, it will result in an int.

so basically it gets evaluated like this (if this helps):

1
2
long long = int * int;   // int*int = int
long long = int;


If you want the multiplication to have a long long result, then you'd have to do the 'num *= i' thing that you're doing, or cast i up to a long long when multiplying:

 
num = (long long)i * i;


why i am getting TLE


I have no idea what TLE is supposed to mean of where that's coming from. What should be happening is num is wrapping to be a negative number (if you're multiplying two positive numbers together).

rather than some sort of exception or error


Overflow is not an exception or error because it's often a desired result.
srry for late reply and thx for such an elaborate explaination :)
btw by TLE i mean "time limit expires" (which is most frequent result of my submissions on online judges :( :P )
thx again
Topic archived. No new replies allowed.