int orders=1000000000;
int mod=pow(10,9)+7;
unsigned int total=4294967295;
total=(orders*(orders+1))%mod;
total/=2;
return total;
expected Answer= 21
BUT getting
runtime error: signed integer overflow: 1000000000 * 1000000001 cannot be represented in type 'int'
I also tried
int orders=1000000000;
int mod=pow(10,9)+7;
long long total=0LL;
total=(long long)(orders*(orders+1))%mod;
total/=2;
return total;
Same error
//Compiled with clang 11 using the latest C++ 17 standard.
May I know why this is happening? I thought maybe long long is getting truncated to int hence the 0LL, But still that didn't solve the issue.
When tried on other compiler, getting output
for 1st code:
-243309312
for second peice of code:
1904174336
powin a program investigating integer behaviour; as we first have to rule out floating point issues before looking at your problem. Why not just type the integer constant to replacepow(10,9)?ordersis anint.(orders*(orders+1))%modis allints(orders*(orders+1))%mod;so the calculation is done signed. The result type on the LHS of the assignment operator does not participate in the type conversions of the expression on the RHS until the expression has ben evaluated and the result is about to be assigned. Note that(a * b) mod m == ((a mod m) * (b mod m)) mod m