I tried submitting a solution for the Calculator problem from the recently concluded July Challenge.
The first submission fetched me a partial result whereas the second submission fetched full points. The only change I did was that I added long long to the third argument of the function findans. Can someone explain the intricacy behind this please?
Its this line-
long long int ans=(n-(b*x))*x;
To explain it clearly, let me first recount a very common example-
int b=5,c=2; double a; a=b/c;
We all know that value of a here is 2, not 2.5, despite being double, and we explain it by saying that both 5 and 2 are int, so data is kept in int-type and not promoted to double before storing.
Similarly, here, when you do
(n-(b*x))*x it keeps the result in int (just like case above), DOES NOT promote it to long long int, due to which overflow happens. Then this overflowed result is stored in variable, which is declared long long int. But when x is long long int, it automatically promotes the expression to higher data type (long long int) and this prevents overflow.