Data type confusion

Hi! I want to know that here to what range of data can I assign the data type int or long or long long. I’ve read in many answers that int type works fine with constraints up to 10^9. But, if it is so, then, why this solution didn’t work even when constraints on N were that N<=10^5?

Range of int…

-2^31 to 2^31
2^31 is approx 2*10^9

now when you multiply 2 ints the intermediate temporary variable is also an int.

(10^5)*(10^5-1) exceeds the range (as the value is approx 10^10) and wraps around…due to which a wrong value gets stored in the variable.

If ‘n’ would have been long long then this error wouldn’t have occurred as the its range would have been

-2^63 to 2^63
2^63 is approx 10^19

To correct the above solution either make the data type of ‘n’ as ‘long long’ or type cast it to ‘long long’ while you are multiplying…

((long long)n)*(n-1)/2

here typecasting even one will work as the intermediate temp variable would be of the higher of the 2 types…i.e. ‘long long’!!

Hope this helps…:slight_smile:

I did it in the second attempt by making it long long. I just wanted to be sure of this range because I have read on many forums people writing “Here, on Codechef, even for given constraints of 10^9, int works fine.” Thank you for clearing the doubt! :slight_smile: