Okay, let me explain this with an example.
int a=3;
int b=2;
double c=a/b;
The value stored in c is NOT 1.5, its 1.0. Its explained as- c = (int)3/(int)2 = (int)(3/2) = (int)(1.5)=1 = 1.0 (since c is double).
Similarly, in sum+=(n3x(3+ n3x3))/2;
after all the multiplication, overflow will occur. Then this overflowed result will get stored in sum. Declaring sum long long int means that sum can store upto K x 10^18, but if overflow occured before storing in sum, then its a problem.
`actually my main doubt is this only n3*n3 will have a type int according to u so how do you determined it. is the type of a "expression" same as of its variables?`
Quoting and answering-
only n3*n3 will have a type int
Yes. But point is, damage is already done. (int)10^9 x 10^9 =(int) 10^18 = -912232384 (some random garbage value after overflow).
so how do you determined it
This is basic knowledge of how your language works. Behind the scene knowledge comes handy many times.
is the type of a "expression" same as of its variables?
Yes. The expression is the type of “Highest” or “largest data type” encountered till now. Lets take this example-
int a=1000000; //a=10^6
long long int b=1;
long long int c=b+a*a;
How will this execute?
Firstly, remember the operator precedence. Although b (long long int) is written first in expression, the first thing computer evaluates is a x a (operator precedence).
So first it becomes a x a= 10^12 = -38438247 (random overflow value).
Then, c= b+ (-38438247) = -38438246 (type-long long int)
When we declare c as long long int while expression is int, then it means it wont overflow under conditions where overall indiviually expression remains int, but if summed over some range, it will cross int.
Eg-
for(i=0;i<100000;i++)
sum+= 1000*100;//Assuming sum is long long int - no overflow.
Here, the entire expression of 1000 x 100 = 10^5 remains within int range, however when summed up for all i, it becomes 10^10. But, no overflow will happen if we declare sum as long long int here.
In your case, the expression crosses the threshold of int, so you need to manually type case it to higher data type, or convert suitable variables to higher data type.