Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can batch files not process large numbers?

Tags:

batch-file

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.

enter image description here

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.

like image 944
Iszi Avatar asked Jul 18 '12 16:07

Iszi


2 Answers

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.

like image 52
Rob Wagner Avatar answered Dec 15 '22 00:12

Rob Wagner


The largest possible integer in a batch file is most likely 2,147,483,647 (the maximum value of a 32 bit signed integer).

like image 36
Robert Harvey Avatar answered Dec 15 '22 01:12

Robert Harvey