Skip to content
gdm9000 edited this page Jun 12, 2017 · 2 revisions

The venerable Windows batch file needs little introduction; let's try anyway. Around since the earliest days of DOS right up through Windows 7, it's the operating system's built-in scripting language. MS has attempted to replace it a few times with Windows Script Host and Windows PowerShell, yet it remains, albeit being modernized a few times along the way. Here's a version of Euler1 in a slightly antiquated style:

:: Euler1 in Windows batch
@ECHO OFF
GOTO main

:euler1
    IF %size% equ 0 (GOTO :end)

    SET /A mod3 = %size% %% 3
    SET /A mod5 = %size% %% 5

    IF %mod3% equ 0 (
        SET /A result += %size%
    ) ELSE (IF %mod5% equ 0 (
        SET /A result += %size%
    ))

    SET /A size -= 1
    GOTO euler1

:main
    SET /A result = 0
    SET /A size = 999

    GOTO euler1
    ECHO "A"

:end
    ECHO %result%

Notice that GOTO is the primary control structure here. It has no support for subroutines, so we've simulated one with labels. And "parameters" are "passed" by setting environmental variables. Quite crude, but it works.

Later on, MS added crude support for subroutines and parameter passing. The runtime still tries to evaluate as much as possible before executing anything, so we need to add the declaration SETLOCAL ENABLEDELAYEDEXPANSION to allow variables within the loop to evaluate correctly:

:: Euler1 in Windows batch
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
GOTO main

:euler1
    SET /A result = 0
    for /l %%i in (1,1,%1) do (
        SET /A mod3 = %%i %% 3
        SET /A mod5 = %%i %% 5

        IF !mod3! equ 0 (
           SET /A result += %%i
        ) ELSE ( IF !mod5! equ 0 (
           SET /A result += %%i
        ))
    )
    GOTO :eof

:main
    CALL :euler1 999
    ECHO !result!

ENDLOCAL

Here’s one more – an elegant algorithm based on an observation by little Carl Friedrich Gauss. It operates in O(1) constant time. Don’t sweat it if this seems inscrutable; click the blog link above for an explanation:

:: Euler1 in Windows batch
@ECHO OFF
GOTO main

:mySum
    SET /A retval = (%1 * (((%2/%1)*(%2/%1) + (%2/%1)) / 2))
    GOTO :eof

:euler1
    CALL :mySum 3 %1
    SET /A three = %retval%
    CALL :mySum 5 %1
    SET /A five = %retval%
    CALL :mySum 15 %1
    SET /A fifteen = %retval%

    SET /A result = %three% + %five% - %fifteen%
    GOTO :eof

:main
    SET /A result = 0
    CALL :euler1 999
    ECHO %result%

Obviously this is DOS/Windows-only. No installation - just execute your file:

C:\>euler1.bat
233168

C:\>
Clone this wiki locally