This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

I am in a situation where I can not use unsigned long or any other variable type.

I must use long.

My problem is that I ran into a situation where I may have two extremly large long values that need to be added together with the result put into another long variable.

Example:

long x = 1178610030

long y = 1115152266

x + y = ?

I think a long has a limit of 2147483647 so if I add x + y my results are not what I should expect.

I actually get a negative number. This means I can't check to see if the result is larger than the limit of a long type.

Is there an easy way to check to see if the sum is larger than the limit of a long?

I must use long.

My problem is that I ran into a situation where I may have two extremly large long values that need to be added together with the result put into another long variable.

Example:

long x = 1178610030

long y = 1115152266

x + y = ?

I think a long has a limit of 2147483647 so if I add x + y my results are not what I should expect.

I actually get a negative number. This means I can't check to see if the result is larger than the limit of a long type.

Is there an easy way to check to see if the sum is larger than the limit of a long?

if(x > 0 && y > 0 && (x + y) < 0)

{

// Error

}

The only way that the error could happen is if both numbers are positive and the sum is negative. You could do bitmasking too, but this is probably more clean.

Something like this:

__int64 x = 1178610030;

__int64 y = 1115152266;

__int64 result = x+y;

__int64 mask31 = ~((__int64) 0x7FFFFFFF); // mask to detect if a bit past 31th is on

if (result & mask31) {

// error

}

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.

If unsigned long won't help you, then here are some basic rules for additive overflow.

Performing Z = X + Y:

x >0 and y>0: If z < x then overflow occurred

x > 0 and y <= 0: no overflow is possible

x <=0 and y > 0: no overflow is possible

x <= 0 and y <= 0: if (z > x) then overflow occurred

Performing Z = X - Y:

x > 0 and y > 0: no overflow is possible

x > 0 and y <= 0: if z< x then overflow occurred

x <= 0 and y > 0: if z > x then overflow occurred

x <= 0 and y <= 0: if z < x then overflow occurred (only possible when x = 0 and y = -2^31)