How to find large factorials using a batch script - batch-file

#echo off
if %1.==. ( echo Missing parameter! Try passing the number as a parameter like 'factorial 10' without the quotes.
goto end )
setlocal enabledelayedexpansion
set /a count=0
set /a temp=0
set /a digits=1
set /a array1=1
for /L %%i IN (2,1,%1) do (
set /a temp=0
for /L %%j IN ( 1,1,!digits! ) do (
set /a temp=!temp!+!array%%j!*%%i
set /a array%%j=!temp!%%10
set /a temp=!temp!/10 )
set /a index=!digits!+1
for /L %%v IN (!index!,1,!index! ) do (
if !temp! NEQ 0 (
set /a array!index!=!temp!%%10
set /a temp/=10
set /a index+=1 ))
set /a digits=!index!-1)
for /l %%v IN ( !digits!,-1,1 ) do set array=!array!!array%%v!
echo !array!
echo Total # of decimal digits = !digits!
:end
pause
This is what i have gotten so far. It is quite stable under 10! but once i reach 15 or 20 it starts missing out a few digits.
My edit....
#echo off
if %1.==. ( echo Missing parameter! Try passing the number as a parameter like 'factorial 10' without the quotes.
goto end )
setlocal enabledelayedexpansion
set /a count=0
set /a temp=0
set /a digits=1
set /a array1=1
for /L %%i IN (2,1,%1) do (
set /a temp=0
for /L %%j IN ( 1,1,!digits! ) do (
set /a temp=!temp!+!array%%j!*%%i
set /a array%%j=!temp!%%10
set /a temp=!temp!/10 )
for /l %%v IN ( 1,1,30 ) do (
if !temp! neq 0 (
set /a digits+=1
set /a array!digits!=!temp!%%10
set /a temp=!temp!/10
)))
for /l %%v IN ( !digits!,-1,1 ) do set array=!array!!array%%v!
echo !array!
echo Total # of decimal digits = !digits!
:end
pause
Now i am forcing the the last inner loop to run 30 times eventhough temp would have been zero way before that. Is there any way to write a snippet that would be analogous to the following c code
while (temp)
{/code goes here/}
This execute only as long as temp is non zero.
Is there any partyicular limit to how big a variable can be in a batch?
I know it is a pain * to debug computational programs in a batch, I'm just trying to code this in all programming languages i know, Just so i could compare their speeds. Can somebody Please point out what i'm doing wrong here.
edit........22/12/13
#echo off
if %1.==. ( echo Missing parameter! Try passing the number as a parameter like 'factorial 10' without the quotes.
goto end )
setlocal enabledelayedexpansion
set /a count=0
set /a tempo=0
set /a digits=1
set /a array1=1
for /f "tokens=1-4 delims=:.," %%a IN ("%time%") do (
set /a "start=(((%%a*60)+1%%b %% 100)*60+1%%c %%100)*100+1%%d %% 100"
)
for /L %%i IN (2,1,%1) do (
set /a tempo=0
for /L %%j IN ( 1,1,!digits! ) do (
set /a tempo=!tempo!+!array%%j!*%%i
set /a array%%j=!tempo!%%10000
set /a tempo=!tempo!/10000 )
for /l %%v IN (1,1,2) do (
if !tempo! neq 0 (
set /a digits+=1
set /a array!digits!=tempo%%10000
set /a tempo=tempo/10000
))
)
for /l %%v IN ( !digits!,-1,1 ) do set array=!array!!array%%v!
echo !array!
echo Total # of decimal digits = !digits!
for /f "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /a "end=(((%%a*60)+1%%b %% 100)*60+1%%c %%100)*100+1%%d %% 100"
)
set /a elapsedcs=end-start
set /a elapseds=elapsedcs/100
set /a elapsedcs=elapsedcs%%100
echo %elapseds%.%elapsedcs% seconds
:end
rem label should never be the last statement
Is this what you meant aacini?

In order to achieve fast arithmetic operations on Big numbers in Batch, you must split the Bignum in groups of digits that can be managed via the 32-bits operations of set /A command. The maximum 32-bits signed integer is 2147483647, so the largest group of digits that can be multiplied this way is 4, because 5 digits (99999 x 99999) exceed the maximum number. Addition and multiplication must be achieved from right to left translating a "carry" to the next group to the left. Subtraction and division must be achieved from left to right translating a "borrow" to the next group to the right. The Batch file below use this method to succesively multiply a Bignum by a 4 digits factor, so it can calculate up to 9999! as long as all variables that contain the groups of 4 digits fits in the 64 MB size limit of the environment (look for "65,536KB maximum size" under "Setting environment variables"). The result is directly output to the screen in order to avoid the 8192 digits limit of one Batch variable.
EDIT: I slightly modified the program in order to run faster and get the number of digits in the result.
#echo off
if "%1" equ "" (
echo Missing parameter! Try passing the number as a parameter like 'factorial 10' without the quotes.
goto end
)
setlocal EnableDelayedExpansion
rem Calculate the factorial
set /A g1=1, groups=1
for /L %%n in (2,1,%1) do (
set carry=0
for /L %%g in (1,1,!groups!) do (
set /A group=g%%g*%%n+carry, g%%g=group%%10000, carry=group/10000
)
if !carry! neq 0 (
set /A groups+=1
set g!groups!=!carry!
)
)
rem Show the factorial
set /P "=!g%groups%!" < NUL
set /A groupsM1=groups-1
for /L %%g in (%groupsM1%,-1,1) do (
set group=000!g%%g!
set /P "=!group:~-4!" < NUL
)
echo/
rem Get the number of digits
set digits=0
for /L %%i in (0,1,3) do if "!g%groups%:~%%i,1!" neq "" set /A digits+=1
set /A digits+=4*groupsM1
echo Total # of decimal digits = %digits%
:end
pause

I had to rereread the code to see what it is doing. Nice.
You have to face three limits on your code.
1 - In the inner %%j and %%v loop, where buffer is used to multiply the current value in %%i, you face the limit indicated by Magoo. You can not operate with set /a with values greater than 2^31. As the values in the array are limited to 0-9, this means that this limit will not let you calculate factorials of numbers greater than 214748364 (aprox)
2 - There is a limit in the size of a environment variable. It can not hold more than 32767 characters. As you are concatenating the digits to output to console (the next limit is related), this limits you to factorials of numbers below 9273 (aprox).
3 - There is a limit in the length of the lines cmd can handle. It is 8191 characters. This does not limit your calc, but you can not use the method of concatenating in a variable to represent the number. If the method is not changed, this limits you to factorials of numbers below 2727 (aprox).

Batch is limited to signed-32-bit integers.
BTW - don't use temp or tmp as a user-variable. It is set by the system as a pointer to a directory where temporary files are stored.

Related

Batch file multiply positive variables return a negative number

I've been working on a Batch polygon area calculator and I got a problem.
I need to multiply 2 variables, but sometimes it return a negative number if the two positive variables are large.
Here's an example: 999999*999999 returns -729379967.
Code goes below:
REM Calc square area
:PolySqu
Cls
Echo Polygon Area Calculator
For /L %%P In (1,1,57) Do Echo.
Set /P "InputPolygonCalSqu=Enter one of the line's length in cm :"
Set /A SquArea=InputPolygonCalSqu * InputPolygonCalSqu
Cls
Echo Polygon Area Calculator
For /L %%P In (1,1,57) Do Echo.
Echo The area of this square is %SquArea% cm2.
Pause
Goto :PolygonCal
It seemed the command
Set /A SquArea="InputPolygonCalSqu * InputPolygonCalSqu
doesn't calculate properly.
As others already pointed out, a batch-file natively supports 32-bit signed integer arithmetics only.
The following code constitutes a work-around for multiplying non-negative numbers greater than the limit of 232 − 1 = 2147483647, using pure batch-file commands (let us call it multiply.bat):
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define arguments here:
set "NUM1=%~1"
set "NUM2=%~2"
set "NUM3=%~3"
set "NUM4=%~4"
if defined NUM1 set "NUM1=%NUM1:"=""%
if defined NUM2 set "NUM2=%NUM2:"=""%
if defined NUM3 set "NUM3=%NUM3:"=%
call :VAL_ARGS NUM1 NUM2 NUM4 || exit /B 1
rem // Define constants here:
set /A "DIG=4" & set "PAD="
setlocal EnableDelayedExpansion
for /L %%J in (1,1,%DIG%) do set "PAD=!PAD!0"
endlocal & set "PAD=%PAD%"
rem // Determine string lengths:
call :STR_LEN LEN1 NUM1
call :STR_LEN LEN2 NUM2
set /A "LEN1=(LEN1-1)/DIG*DIG"
set /A "LEN2=(LEN2-1)/DIG*DIG"
set /A "LIM=LEN1+LEN2+DIG"
for /L %%I in (0,%DIG%,%LIM%) do set /A "RES[%%I]=0"
rem // Perform block-wise multiplication:
setlocal EnableDelayedExpansion
for /L %%J in (0,%DIG%,%LEN2%) do (
for /L %%I in (0,%DIG%,%LEN1%) do (
set /A "IDX=%%I+%%J"
if %%I EQU 0 (set "AUX1=-%DIG%") else (
set /A "AUX1=%DIG%+%%I" & set "AUX1=-!AUX1!,-%%I"
)
if %%J EQU 0 (set "AUX2=-%DIG%") else (
set /A "AUX2=%DIG%+%%J" & set "AUX2=-!AUX2!,-%%J"
)
for /F "tokens=1,2" %%M in ("!AUX1! !AUX2!") do (
set "AUX1=!NUM1:~%%M!" & set "AUX2=!NUM2:~%%N!"
)
call :NO_LEAD0 AUX1 !AUX1!
call :NO_LEAD0 AUX2 !AUX2!
set /A "RES[!IDX!]+=AUX1*AUX2"
set /A "NXT=IDX+DIG, DIT=DIG*2"
for /F "tokens=1,2,3" %%M in ("!IDX! !NXT! !DIT!") do (
set "AUX=!RES[%%M]:~-%%O,-%DIG%!"
set /A "RES[%%N]+=AUX"
set "RES[%%M]=!RES[%%M]:~-%DIG%!"
call :NO_LEAD0 RES[%%M] !RES[%%M]!
)
)
)
rem // Build resulting product:
set "RES=" & set "AUX="
for /L %%I in (0,%DIG%,%LIM%) do (
set /A "RES[%%I]+=AUX"
set /A "NXT=%%I+DIG"
for /L %%J in (!NXT!,%DIG%,!NXT!) do (
set "AUX=!RES[%%I]:~-%%J,-%DIG%!"
)
set "RES[%%I]=%PAD%!RES[%%I]!"
set "RES=!RES[%%I]:~-%DIG%!!RES!"
)
endlocal & set "RES=%RES%"
call :NO_LEAD0 RES %RES%
rem // Return resulting product:
echo(%RES%
if defined NUM3 (
endlocal
set "%NUM3%=%RES%"
) else (
endlocal
)
exit /B
:NO_LEAD0 rtn_var val_num
rem // Remove leading zeros from a number:
for /F "tokens=* delims=0" %%Z in ("%~2") do (
set "%~1=%%Z" & if not defined %~1 set "%~1=0"
)
exit /B 0
:STR_LEN rtn_length ref_string
rem // Retrieve length of string:
setlocal EnableDelayedExpansion
set "STR=!%~2!"
if not defined STR (set /A LEN=0) else (set /A LEN=1)
for %%L in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if defined STR (
set "INT=!STR:~%%L!"
if not "!INT!"=="" set /A LEN+=%%L & set "STR=!INT!"
)
)
endlocal & set "%~1=%LEN%"
exit /B 0
:VAL_ARGS ref_arg1 ref_arg2 ref_arg3
rem // Check arguments for validity:
if not defined %~1 >&2 echo ERROR: too few arguments given! & exit /B 1
if not defined %~2 >&2 echo ERROR: too few arguments given! & exit /B 1
if defined %~3 >&2 echo ERROR: too many arguments given! & exit /B 1
(call echo "%%%~1%%" | > nul findstr /R /C:"^\"[0-9][0-9]*\" $") || (
>&2 echo ERROR: argument 1 is not purely numeric! & exit /B 1
)
(call echo "%%%~2%%" | > nul findstr /R /C:"^\"[0-9][0-9]*\" $") || (
>&2 echo ERROR: argument 2 is not purely numeric! & exit /B 1
)
exit /B 0
To use it provide the two numbers to multiply as command line arguments; for instance:
multiply.bat 999999 999999
The resulting product is returned on the console:
999998000001
If you provide a third argument, the product is assigned to a variable with that name; for example:
multiply.bat 999999 999999 SquArea
This sets variable SquArea to the resulting value. The latter is also still returned on the console.
To silently assign the variable without any additional console output, redirect it to the nul device:
multiply.bat 999999 999999 SquArea > nul
Batch uses 32bit integers for storing numbers. This gives them a maximum size of 2^31 - 1 = 2,147,483,647.
999,999 * 999,999 = 999,998,000,001 which is larger than 2,147,483,647 therefore it "wraps" and starts from negatives.
This is a limitation of batch although there are some workarounds.
This might be useful
Can batch files not process large numbers?
The largest number batch can take is 2^31 - 1 = 2,147,483,647.
So again, it is starting back from negative and giving you that answer..
I noticed using pure batch, it would be somewhat to very difficult to implement operations that support the numbers beyond the 32-bit integer limit. So instead, I limited the numbers, so they won't overflow when multiplied.
REM Calc Square Area
:PolySqu
Cls
Echo Polygon Area Calculator
For /L %%P In (1,1,57) Do Echo.
Set /P "InputPolygonCalSqu=Enter one of the line's length in cm [Less then 40000] :"
If %InputPolygonCalSqu% GTR 40000 Goto :PolySqu
Set /A SquArea="InputPolygonCalSqu * InputPolygonCalSqu
Cls
Echo Polygon Area Calculator
For /L %%P In (1,1,57) Do Echo.
Echo The area of this square is %SquArea% cm2.
Pause
Goto :PolygonCal

how can i get disk space with decimal point in gb tb and mb [duplicate]

This question already has answers here:
Using wmic to get drives space information
(3 answers)
Closed 6 years ago.
I am trying to get the disk space in if it is MB GB or TB with 2 decimal part.
It should give the output with decimals
Here is my code:
WMIC LOGICALDISK GET Name,Size,FreeSpace | find /i "C:"
This is the slightly modified script from my answer to another question, which constitutes a pure batch-file solution: Get size of a directory in 'MB' using batch file.
Basically, all computations are done with numbers padded by two zeros to the right, which is the same as multiplying by a hundred, and the decimal separator is inserted next to the second digit from the right just for displaying. The drive to get the free space of needs to be given as a command line argument, like C: for example.
Here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Define constants here:
set /A DIVISOR=1024 & rem (1024 Bytes = 1 KiB, 1024 KiB = 1 MiB,...)
set "ROUNDUP=" & rem (set to non-empty value to round up results)
set /A DECIMALS=2 & rem (define number of decimal places here)
set "PAD=" & for /L %%N in (1,1,%DECIMALS%) do call set "PAD=%%PAD%%0"
rem Get free space size of drive given as command line argument:
for /F "tokens=2 delims== " %%B in ('
wmic LogicalDisk WHERE 'DeviceID^="%~1"' GET FreeSpace /VALUE
') do for /F %%A in ("%%B") do set "BYTES=%%A"
if not defined BYTES set "BYTES=0"
rem Display result in Bytes and divide it to get KiB, MiB, etc.:
call :DIVIDE %BYTES%%PAD% 1 RESULT
call :DISPLAY %RESULT% %DECIMALS% STRING
echo( Bytes: %STRING%
call :DIVIDE %RESULT% %DIVISOR% RESULT REST
if defined ROUNDUP if 0%REST% GTR 0 set /A RESULT+=1
call :DISPLAY %RESULT% %DECIMALS% STRING
echo(KiBytes: %STRING%
call :DIVIDE %RESULT% %DIVISOR% RESULT REST
if defined ROUNDUP if 0%REST% GTR 0 set /A RESULT+=1
call :DISPLAY %RESULT% %DECIMALS% STRING
echo(MiBytes: %STRING%
call :DIVIDE %RESULT% %DIVISOR% RESULT REST
if defined ROUNDUP if 0%REST% GTR 0 set /A RESULT+=1
call :DISPLAY %RESULT% %DECIMALS% STRING
echo(GiBytes: %STRING%
call :DIVIDE %RESULT% %DIVISOR% RESULT REST
if defined ROUNDUP if 0%REST% GTR 0 set /A RESULT+=1
call :DISPLAY %RESULT% %DECIMALS% STRING
echo(TiBytes: %STRING%
endlocal
exit /B
:DIVIDE val_dividend val_divisor [ref_result] [ref_remainder]
rem Divide a huge number exceeding the 32-bit limitation
rem by a 32-bit number in the range from 1 to 1000000000;
rem the result might also exceed the 32-bit limitation.
setlocal EnableDelayedExpansion
set "DIVIDEND=%~1"
set "DIVISOR=%~2"
set "QUOTIENT=%~3"
set "REMAINDER=%~4"
rem Check whether dividend and divisor are given:
if not defined DIVIDEND (
>&2 echo(Too few arguments, dividend missing^^!
exit /B 2
) else if not defined DIVISOR (
>&2 echo(Too few arguments, divisor missing^^!
exit /B 2
)
rem Check whether dividend is purely numeric:
for /F "tokens=* delims=0123456789" %%N in ("!DIVIDEND!") do (
if not "%%N"=="" (
>&2 echo(Dividend must be numeric^^!
exit /B 2
)
)
rem Convert divisor to numeric value without leading zeros:
for /F "tokens=* delims=0" %%N in ("%DIVISOR%") do set "DIVISOR=%%N"
set /A DIVISOR+=0
rem Check divisor against its range:
if %DIVISOR% LEQ 0 (
>&2 echo(Divisor value must be positive^^!
exit /B 1
) else if %DIVISOR% GTR 1000000000 (
>&2 echo(Divisor value exceeds its limit^^!
exit /B 1
)
set "COLL=" & set "NEXT=" & set /A INDEX=0
rem Do a division digit by digit as one would do it on paper:
:LOOP
if "!DIVIDEND:~%INDEX%,1!"=="" goto :CONT
set "NEXT=!NEXT!!DIVIDEND:~%INDEX%,1!"
rem Remove trailing zeros as such denote octal numbers:
for /F "tokens=* delims=0" %%N in ("!NEXT!") do set "NEXT=%%N"
set /A NEXT+=0
set /A PART=NEXT/DIVISOR
set "COLL=!COLL!!PART!"
set /A NEXT-=PART*DIVISOR
set /A INDEX+=1
goto :LOOP
:CONT
rem Remove trailing zeros as such denote octal numbers:
for /F "tokens=* delims=0" %%N in ("%COLL%") do set "COLL=%%N"
if not defined COLL set "COLL=0"
rem Set return variables or display result if none are given:
if defined QUOTIENT (
if defined REMAINDER (
endlocal
set "%REMAINDER%=%NEXT%"
) else (
endlocal
)
set "%QUOTIENT%=%COLL%"
) else (
endlocal
echo(%COLL%
)
exit /B
:DISPLAY val_number val_decimals [ref_result]
rem Prepare fractional number for being displayed.
setlocal EnableDelayedExpansion
set "NUM=%~1"
set "DEC=%~2"
set "SEP=."
set "RET=%~3"
set "PAD=" & for /L %%N in (1,1,%DEC%) do set "PAD=!PAD!0"
set "NUM=%PAD%%NUM%"
set "NUM=!NUM:~,-%DEC%!%SEP%!NUM:~-%DEC%!"
for /F "tokens=* delims=0" %%N in ("%NUM%") do set "NUM=%%N"
if "%NUM:~,1%"=="%SEP%" set "NUM=0%NUM%"
if defined RET (
endlocal
set "%RET%=%NUM%"
) else (
endlocal
echo(%NUM%
)
endlocal
exit /B
Here is a sample output (supposing the script is saved as drive-size.bat):
C:\TEMP>drive-size.bat C:
Bytes: 82752724992.00
KiBytes: 80813208.00
MiBytes: 78919.14
GiBytes: 77.06
TiBytes: 0.07

Batch - Decreasing value of a variable in substring is not functioning

I'm trying to reverse "hello" to "olleh". But the output shows "ooooo".
I think !string:~%back%,1! is the problem, because when I use echo to test the value of back is decreasing or not, it works, but it doesn't work in substring, so it always get the last character of the string (-1,1).
#echo off
set string=hello
set temp_string=%string%
set /a string_length=0
:find_length
if defined temp_string (
set temp_string=%temp_string:~1%
set /a string_length+=1
goto :find_length
)
:loop
setlocal enabledelayedexpansion
set /a back=-1
for /l %%a in (1,1,!string_length!) do (
set reverse_string=!string:~%back%,1!!reverse_string!
set /a back-=1
)
echo !reverse_string!
pause >nul
As TripeHound commented, %back% needs to be delayed. What you should do is use the for /L loop value of %%a to in place of %back%. (No sense decrementing a variable manually when one's already being decremented for you as a part of the for /L loop, right?)
for /l %%a in (%string_length%,-1,0) do (
call set "reverse_string=!reverse_string!!string:~%%a,1!"
)
goto loops are not very efficient. If you've got a long string you're going to reverse, there'll be a noticeable pause while you count its length if you goto :label for each character. The fastest way I've found to get the length of a string is based on jeb's answer here:
:length <return_var> <string>
setlocal enabledelayedexpansion
if "%~2"=="" (set ret=0) else set ret=1
set "tmpstr=%~2"
for %%I in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if not "!tmpstr:~%%I,1!"=="" (
set /a ret += %%I
set "tmpstr=!tmpstr:~%%I!"
)
)
endlocal & set "%~1=%ret%"
goto :EOF
Put it all together like this:
#echo off
setlocal
set "string=%*"
call :length string_length "%string%"
setlocal enabledelayedexpansion
for /l %%a in (%string_length%,-1,0) do (
set "reverse_string=!reverse_string!!string:~%%a,1!"
)
echo(!reverse_string!
pause >nul
exit /b 0
:length <return_var> <string>
setlocal enabledelayedexpansion
if "%~2"=="" (set ret=0) else set ret=1
set "tmpstr=%~2"
for %%I in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if not "!tmpstr:~%%I,1!"=="" (
set /a ret += %%I
set "tmpstr=!tmpstr:~%%I!"
)
)
endlocal & set "%~1=%ret%"
goto :EOF
Example output:
command: test.bat The quick brown fox
result: xof nworb kciuq ehT
The problem is that %back% is being used without delayed expansion, so will always have the value -1. Replacing the end of your code with:
set /a back=-1
set /a count=1
:repeat
if %count% gtr %string_length% goto :report
set reverse_string=!string:~%back%,1!!reverse_string!
set /a back-=1
set /a count+=1
goto :repeat
:report
echo !reverse_string!
Will do the trick.
You cannot just use !back! because you need the contrast of !...! and %...% to have a variable index, so you'll have to go back to an old-fashioned :loop construct so %back% gets updated each time around.
As described at this post:
"To get the value of a substring when the index change inside FOR/IF enclose the substring in double percents and precede the command with call. For example:
for /l %%a in (1,1,!string_length!) do (
call set reverse_string=%%string:~!back!,1%%!reverse_string!
set /a back-=1
)
Another way to achieve previous process is using an additional FOR command to change the delayed expansion of the index by an equivalent replaceable parameter, and then use the delayed expansion for the substring. This method run faster than previous CALL:
for /l %%a in (1,1,!string_length!) do (
for %%b in (!back!) do (
set reverse_string=!string:~%%b,1!!reverse_string!
)
set /a back-=1
)
"
However, it is not efficient to first loop thru the string just to count the characters, and then loop again to reverse they. I think the method below should be the fastest one:
#echo off
setlocal EnableDelayedExpansion
set maxLength=80
set string=hello
set "reverse="
for /L %%i in (1,1,%maxLength%) do (
set "reverse=!string:~0,1!!reverse!"
set "string=!string:~1!"
if not defined string goto break
)
:break
echo %reverse%
Here's another algorithm:
#echo off
call :reverse "The quick brown fox"
echo %output%
pause & exit
:reverse
setlocal enableDelayedExpansion
set string=%~1
set index=0
:loopchar
set char=!string:~%index%,1!
if "!char!"=="" endlocal & set output=%output% & exit /b
set output=!char!!output!
set /a index+=1
goto loopchar
"Tricks":
using %index% inside ! to expand its current value instead of call with %% (#Aacini)
export of !output! from the local scope by reassigning it on the same line as endlocal.

How do I concatenate the value of a variable into the name of another in a batch file?

So I've been writing a batch file which backs up a certain file while cleaning old entries every so often. I've run into an issue where it would be simpler and more readable to store month lengths (for calculation purpose) (days1,days2,days3,etc.), and reference these by concatenating the word days with a variable which stores the month (1, 2, 3, etc.). Unfortunately, this never seems to reference the right variable correctly. Here's the relevant code, from a section calculating a date 28 days previously:
set days1=31
set days2=28
set days3=31
set days4=30
set days5=31
(etc.)
...
set pastmonthday=%curday%-28
set pastmonthmonth=%curmonth%
set pastmonthyear=%curyear%
if %pastmonthday% lss 0 (
set /a pastmonthmonth=%pastmonthmonth%-1
set /a pastmonthprevmon=1
)
if %pastmonthmonth%==0 (
set /a pastmonthyear-=1
set /a pastmonthmonth=12
)
set monthlengthvar=0
setlocal EnableDelayedExpansion
set tempmonthlengthvar=0
if %pastmonthday% lss 0 (set tempmonthlengthvar = !days%pastmonthmonth%!)
echo.%tempmonthlengthvar%
pause
for /F "delims=" %%A in (!tempmonthlengthvar!) DO (
endlocal
set "monthlengthvar=%%A"
)
set pastmonthday+=%monthlengthvar%
echo.%pastmonthday%
pause
...
The two echoes output 0 and -7, respectively. I can't figure out why this is, no matter how I've reworked it.
some errors (forgotten /a in set, quotes etc.)
#ECHO OFF &SETLOCAL disableDelayedExpansion
SET /a days1=31
set /a days2=28
set /a days3=31
set /a days4=30
set /a days5=31
set /a pastmonthday=22-28
set /a pastmonthmonth=2
set /a pastmonthyear=2014
if %pastmonthday% lss 0 (
set /a pastmonthmonth-=1
set /a pastmonthprevmon=1
)
if %pastmonthmonth% equ 0 (
set /a pastmonthyear-=1
set /a pastmonthmonth=12
)
set /a monthlengthvar=0
setlocal EnableDelayedExpansion
set /a tempmonthlengthvar=0
if %pastmonthday% lss 0 SET /a tempmonthlengthvar=!days%pastmonthmonth%!
ECHO(%tempmonthlengthvar%
for /F "delims=" %%A in ("%tempmonthlengthvar%") DO (
IF "!"=="" endlocal
set /a monthlengthvar=%%A
)
set /a pastmonthday+=monthlengthvar
ECHO(%pastmonthday%

Using an if statement inside a for loop

I am trying to make a batch file to solve the first Project Euler problem, http://projecteuler.net/problem=1, but I need an if statement inside my loop to check if n modulo 3 or 5 is 0. And the sum has suddenly stopped working.
My code:
echo off
set sum=0
for /l %%n in (1,1,999) do (
set a/ sum+=%%n *(only add if n%%3 == 0 or n%%5 == 0)*
)
echo %sum%
pause
Here is a very efficient solution, though it is a bit obfuscated:
#echo off
setlocal
set /a sum=0
for /l %%N in (1 1 999) do set /a "sum+=%%N/!((%%N%%5)*(%%N%%3))" 2>nul
echo %sum%
The expression (%%N%%5)*(%%N%%3) yields zero if %%N is divisible by 3 or 5, or non-zero if it is not divisible by either. The ! takes the inverse logical value, so 0 becomes 1, and non-zero becomes 0. Dividing %%N by that expression yields either %%N or a division by zero error. So simply add that entire expression to the sum, and redirect error messages to nul.
Final result - only numbers divisible by 3 or 5 are added :-)
#ECHO OFF
SETLOCAL
set /A sum=0
for /l %%n in (1,1,999) do (
CALL :modulo %%n
IF DEFINED addme set /a sum+=%%n
REM CALL echo %%n %%sum%% %%addme%%
)
echo %sum%
GOTO :EOF
:modulo
:: set addme if %1 %% 3 == 0 or %1 %% 5 == 0
SET /a addme = %1 %% 3
IF %addme%==0 GOTO :EOF
SET /a addme = %1 %% 5
IF %addme%==0 GOTO :EOF
SET "addme="
GOTO :eof
Simply pass each value to the :modulo routine in turn and set a flag value to (clear or not)
OR
#ECHO OFF
SETLOCAL enabledelayedexpansion
set /A sum=0
for /l %%n in (1,1,999) do (
SET /a mod=%%n %% 3
IF NOT !mod!==0 SET /a mod=%%n %% 5
IF !mod!== 0 set /a sum+=%%n
rem CALL echo %%n %%sum%%
)
echo %sum%
GOTO :EOF
which does the same thing using delayedexpansion.
And the sum has suddenly stopped working.
I think your sum stopped working because your set needs to have the slash in front of the 'a', and not behind it, like this:
SET /A sum+=%%n
Also, there isn't an OR operator in DOS Batch, so you'll need to use a nested IF for that. This worked for me:
echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set sum=0
for /l %%n in (1,1,999) do (
SET /A mod3=%%n%%3
SET /A mod5=%%n%%5
IF !mod3!==0 (
SET /A sum+=%%n
) ELSE (
IF !mod5!==0 (
SET /A sum+=%%n
)
)
)
echo %sum%
ENDLOCAL
If you need more help, check out Rob van der Woude's Scripting pages. Specifically, here is a link to his page on performing mathematical operations in DOS batch files.

Resources