0

I created a function seriesSum to return a sum of the series of a number, and I used long long return data type but it returns a negative number if I insert for example 46341 output will be -1073716337 and what I am expected is 1073767311 here is my code:

#include <iostream>
using namespace std;

long long seriesSum(int n)
{return n*(n+1)/2;}

int main()
{
    cout<<seriesSum(46341); // expected 1073767311 but output is -1073716337

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 2
    Change parameter to `unsigned long long int n`. – Jason Oct 15 '22 at 08:06
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of related SO posts for this. – Jason Oct 15 '22 at 08:14
  • The reason is also explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) which are also available as PDFs for free. – Jason Oct 15 '22 at 08:16
  • `46341*46342` overflows, and in this case is `-2147432674` (but is **undefined behavior**). `-2147432674/2` is `-1073716337`. Mystery solved. – Eljay Oct 15 '22 at 11:39

2 Answers2

2

The argument variable n is an int.

All operations you perform in the function are done using int values. Which you will overflow, leading to undefined behavior.

Change the argument type to unsigned long long.

I also recommend you change the return type to be unsigned as well, if you're not going to get negative results.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

The problem with the code is that you are using objects of the type int in this expression statement

return n*(n+1)/2;

instead of objects of the type long long int.

You could write for example

long long seriesSum(int n)
{
    return n % 2 == 0 ? n / 2ll * ( n + 1ll ) : ( n + 1ll ) / 2ll * n;
}

Though as the sum is calculated for non-negative numbers then it is better to declare the function like

unsigned long long seriesSum( unsigned int n )
{
    return n % 2 == 0 ? n / 2llu * ( n + 1llu ) : ( n + 1llu ) / 2llu * n;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335