Factorial Calculation in Batch

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
lol :hysterical:

Code:
@echo off
setlocal enabledelayedexpansion
for /l %%G in (0,1,12) do (
    set /a n=%%G
) & call :Factorial !n! & echo %%G^^! = !_Factorial!
pause & goto :eof

:Factorial
set _Factorial=1
call :calc_factorial %1 & goto :eof
    :calc_factorial
    set /a num=%1
    if %num% gtr 1 (
        set /a _Factorial*=!num!
        call :calc_factorial !num!-1
    )
goto :eof

Here's a recursive script I came up with earlier. It was fun, I got to see this message for a while until I fixed out the bugs in my script:

Code:
**  B A T C H   R E C U R S I O N  exceeds STACK limits **
Recursion Count=394, Stack Usage=90 percent
**  B A T C H   PROCESSING IS   A B O R T E D  **

Sad thing is, because batch only supports 32 bit integers as far as I know, the maximum it can calculate up to is 12!. 0! to 12! will yield all accurate results.... Anything past that is too larger for a 32 bit integer; almighty batch scripting. :thumbsup2:
 
If you try to implement recursion that goes into too many branches (or "depth" levels), then you'll see it. :)

Personally I think the limitation on the depth for batch is a bit lame. It's not very high... haha.

edit: Here is the output, as an example, for what my script above does:
iz4QtZx.png


Sadly these are the only values that you can possibly calculate in batch with it's 32 bit integer data type limitation. You would need some kind of workaround to generate higher values, otherwise, you would probably just have to store known factorial values higher than 12! in predefined variables lol.
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top