Help in L-R Queries

Why is this solution failing in first subtask even though I used long where it is needed. After that I used long for all the variables where they won’t even overflow as they were given in constraint as 1<=Ai,
Y<=10e9. The same solution with every data type set as long is passing here. Please explain.

You may refer this discussion for lunchtime problems

https://discuss.codechef.com/questions/118551/discuss-your-approach-november-lunchtime

@taran_1407 If you can please see where my answer is giving WA for first soluiton. It is just a naive implementation of the problem. I don’t know why it is giving WA for first solution and AC for second where I used long even where it is not needed.

The difference in both the solutions is the use of data types int vs long.

when you calculate (curr-l)*(r-curr) with curr, l and r upto 10e9, It overflows.

But when you use long, it doesn’t

The problem is in the following line:

  • long sum = ((curr - l) * (r - curr));

You need to understand how the expression is evaluated. Assigning answer to the long variable does not make the calculation in long. Here curr is int, l is int and r is int. i.e. all variables are of int type. So, the expression is get evaluated in int only and then it is assigned to long variable-sum. To get evaluation in long, you need to either declare some variable in long type or use typecasting in expression. So, the correct expression is:

  • long sum = ((long)(curr - l) * (r - curr));

Here, (curr-l) is typecasted to long, so (r-curr) is promoted to long from int and expression is get evaluated in long and then the answer is ansigned to long sum.

1 Like

Thank you. Will keep this in mind from next time.