Solving Problem 1 Using Windows Batch files

As crazy a it sounds, it turns out it is possible to solve Project Euler problem 1 using Windows Batch files! It is possible because modern versions for cmd support delayed expansion of variables, and arithmetic expressions using “SET /A”.

Delayed expansion means that variables are expanded at runtime, rather than parse time. Normally %VARIABLE% will be expanded once with whatever value it contains before the script is run, however with delayed expansion we can use !VARIABLE!. This variable is expanded whenever that line is executed, which with a for loop could be multiple times.

@echo off
setlocal enabledelayedexpansion

set /a sum = 0
FOR /L %%L IN (1, 1, 999) DO (
    set /a mod = %%L %% 3
    IF NOT !mod! EQU 0 set /a mod = %%L %% 5
    IF !mod! EQU 0 set /a sum = sum + %%L
)

echo %sum%
endlocal