2

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

3 Answers 3

5

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

0
@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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.