For the sake of my own amusement, I decided to try writing a batch file to calculate Hailstone Sequences. However, I ran into a small problem with some large-ish numbers.
First, the code:
:START
@ECHO OFF
SETLOCAL
SET /P InputVar="Input Number: "
ECHO.
ECHO %InputVar%
SET ItCount=0
:COLLATZ
SET /A ItCount=%ItCount%+1
SET /A Odd=%InputVar%%%2
IF %Odd% EQU 1 (
SET /A OutputNum=%InputVar%*3+1
) ELSE (
SET /A OutputNum=%InputVar%/2
)
ECHO %OutputNum%
IF %OutputNum% LSS 1 (
GOTO ERROR
) ELSE (
GOTO RECYCLE
)
:ERROR
ECHO.
ECHO ERROR!
GOTO END
:RECYCLE
IF %OutputNum% EQU 1 (
GOTO FINISH
) ELSE (
SET InputVar=%OutputNum%
GOTO COLLATZ
)
:FINISH
ECHO.
ECHO Completed in %ItCount% iterations.
:END
ENDLOCAL
PAUSE
This works for several numbers I've tested. However, when I got around to testing a number that I new would take hundreds of iterations to complete, the system started returning negative outputs. Interestingly, the negative outputs eventually resolved to zero. However, this behavior of the script is not at all expected or intended.
After adding in the error handling, this is the output I get for 8388607
.
According to Google, the next number should have been 2176782334
.
Is this a natural limitation of the command processor's ability to handle large numbers? Similar operations run fine in Excel - there, I was able to determine the number should have resolved to 1 in 473 iterations.
I'm running Windows 7 SP1 x64.
2176782334 is larger than an 32bit integer can hold. (2^31 - 1 = 2,147,483,647). What you are experiencing is integer overflow, (causing negative values).
Most modern languages have a datatype long
that will allow you to hold integers in the range of -2^64 to 2^64 -1. There are even data types to allow infinite precision integers, like Java's BigInteger
.
The largest possible integer in a batch file is most likely 2,147,483,647 (the maximum value of a 32 bit signed integer).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With