Wednesday, October 22, 2014

Project Euler in CMD: Multiples of 3 and 5

cmd.exe by *n3wjack's world in pixels is licensed CC BY-SA 2.0
One of the fun parts about working at a college is the intellectual cross-pollination that occurs here from time to time. Today, for example, our programming instructor came up to me and told me about Project Euler, which maintains a list of increasingly difficult mathematics/computer problems. Since this seemed like as good of time as any to brush up on my scripting skills and to show him the anachronistic horror that is Windows CMD Shell syntax, I thought it would be fun to start implementing them as batch scripts. Here's my solution for the easiest of the bunch - Problem 1:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
My solution, which gives an answer of 233,168:

@ECHO OFF
SET _Sum=0
FOR /L %%G IN (1,1,999) DO (CALL :ThreeByFive %%G)
ECHO %_Sum%
GOTO :eof

:: Our "function" - checks if a number is evenly divisible by 
:: 3, 5, or both, and adds the number if so.
:ThreeByFive
 :: Keep most of our variables in local scope
 SETLOCAL

 :: Check for divisibility.
 SET /A "_ModF=%1%%5"
 SET /A "_ModT=%1%%3"

 :: Now to perform some tests. Note the use of a 
 :: GOTO statement to skip a check if one passes.
 IF %_ModT% EQU 0 GOTO SumVal
 IF %_ModF% EQU 0 GOTO SumVal

 :: Failed all checks - end subroutine
 GOTO :eof

 :: Passed at least one of the checks - add the number!
 :SumVal
 ENDLOCAL & SET /A "_Sum+=%1"
 GOTO :eof

For what it's worth, he found the syntax suitably horrifying, especially when I showed him the difference between how CMD handles variables with EnableDelayedExpansion on and with it off while I performed my initial bug and logic testing.

No comments:

Post a Comment