## How to expand the range of integers in C++?

Moderators: phlip, Moderators General, Prelates

Noetherium
Posts: 5
Joined: Sun Feb 06, 2011 9:52 pm UTC

### How to expand the range of integers in C++?

Hey, everyone.

I hope you can help me. I'm currently stuck with Problem 14 from
http://projecteuler.net/index.php?section=problems&id=14
. As soon as my program evaluates 113383, it seems to be stuck in an infinite loop (That also appears later at other numbers if I exclude 113383). I suppose that this is due to an integer overflow in the corresponding Collatz sequence.
I'm working with C++, Windows XP 32-bit, Bloodshed Dev-C++ Vers. 4.9.9.2. Is there any way to expand the range of the corresponding integer variable (i.e. assign more bytes to it)? Else, what can I do to avoid this problem (I have already tried using "unsigned long int").

Regards,

Leon

zed0
Posts: 179
Joined: Sun Dec 17, 2006 11:00 pm UTC

### Re: How to expand the range of integers in C++?

Having done this problem myself I didn't have problems with overflow if I just used long ints everywhere, are you sure that overflows are your problem?

Noetherium
Posts: 5
Joined: Sun Feb 06, 2011 9:52 pm UTC

### Re: How to expand the range of integers in C++?

Actually, yes. I've written a second short program that just shows the Collatz sequence of the input number, and at some point, the numbers are getting negative. I don't see how this can occur without integer overflow. Just for additional details, here is the function I use to compute the next element (which is indeed the Collatz function):

Code: Select all

`int Collatz(int Zahl){    int Ergebnis;    if(Zahl%2==1)    {                 Ergebnis=3*Zahl+1;    }    else    {    Ergebnis=Zahl/2;    }    return Ergebnis;}`

EDIT: Yep, 827370449 is followed by -1812855948. This is integer overflow, isn't it?

Robert'); DROP TABLE *;
Posts: 730
Joined: Mon Sep 08, 2008 6:46 pm UTC
Location: in ur fieldz

### Re: How to expand the range of integers in C++?

Yes, Collatz(827370449) produces a value 32 bits long, the most significant being a 1, hence your overflow. You can patch it by returning a uint instead, and also try "unsigned long long," but you're probably better to find an arbitrary-precision arithmetic library to fix it totally.
...And that is how we know the Earth to be banana-shaped.