-1

its some miscalculation.

I am in trouble with large numbers. this code works for some smaller inputs(N) but for inputs like 100000 it doesn't.

the correct final answer of result variable when N = 100000 must be 4999949998 but result in this code is 704982702

long long result = 0;
int N;
cin >> N;
.
.          //some changes on result
.
result = result / 2;
long long tmp =( N*(N - 1) ) / 2;
result = tmp - result;
cout << result << endl;

but tmp is long long too and it doesn't seems an overflow.

but some simple changes made it correct.

long long result = 0;
int N;
cin >> N;
.
.          //some changes on result
.
result = result / 2;
long long tmp = 0;
for (int i = 1; i < N; i++)
    tmp += N;
tmp = tmp / 2;
result = tmp - result;
cout << result << endl;

I can't find the reason. do you know that?

Csq
  • 5,775
  • 6
  • 26
  • 39
mama23n
  • 135
  • 2
  • 3
  • 10

1 Answers1

4
( N*(N - 1) ) / 2

I this expression, everything is int, therefore the result is calculated in an int and overflows while calculating N*(N - 1).

( static_cast<long long>(N)*(N - 1) ) / 2

Coverting N˙to long long solves the problem, long long mutiplied by an int gives long long result, as expected, same for division.

Csq
  • 5,775
  • 6
  • 26
  • 39