outsiders
outsiders

Reputation: 441

why use int error,but long long right

int c;
long long sum=0;
sum+=c*(c-1)/2;

when c=100000,why sum can't get the right answer? should I write sum+=(long long)(c*(c-1)/2);

Upvotes: 3

Views: 411

Answers (3)

Shashi Bhushan
Shashi Bhushan

Reputation: 1541

In your question c is declared as integer. so it crosses the limit of integer itself in the expression c*(c-1). so overflow occurs.before it gets implicitly converted into long long.Thats the reason behind UB.

whereas when u implicitly converted it into long long u will ger the right answer...

Upvotes: 1

pickypg
pickypg

Reputation: 22332

Because it is using c as an int in the calculations, and widening it when it's stored.

You need to cast one of the c's to a long long before multiplying.

Also, I suggest you look into using int64_t in place of long long so that you can get the actual type/size you want no matter what (see stdint.h for the various identifiers).

Upvotes: 1

Will A
Will A

Reputation: 24998

int here is 32-bit I assume - 100000 squared (10E9) exceeds the maximum range for an int resulting in an overflow. The below would work - casting the first instance of c to long long will mean that the rest of the expression will be "long long compatible".

sum+=((long long)c*(c-1)/2);

Upvotes: 5

Related Questions