Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I got a negative number while trying to return a long long value

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading