Search code examples
windowsbatch-filerandomgenerator

How do I generate a seven digit random number which is itself divisible by seven


I am working on a program, and all of the parts work perfectly except one, that part is supposed to generate a seven digit random number which is divisible by 7.

I am aware that there are similiar questions to mine, but I did not find my anwser within them, and despite trying I was myself only capable of somethimes generating such a number.

Any idea how to do so?


Solution

  • You can use the modulo function (see set /?):

    @echo off
    setlocal
    
    set "number=%random%%random%%random%%random%%random%%random%%random%"
    set "number=%number:~0,7%"
    set /a remainder=number %% 7
    if %remainder% equ 0 (
      echo %number% is a multiple of 7
    ) else (
      echo %number% divided by 7 gives a rest of %remainder%
    )
    

    Just in case, leading zero(s) is/are ok or even desired as a possibility:

    @echo off
    setlocal
    
    set "number=%random%%random%%random%%random%%random%%random%%random%"
    set "number=%number:~-7%"
    set /a remainder=7%number% %% 7
    if %remainder% equ 0 (
      echo %number% is a multiple of 7
    ) else (
      echo %number% divided by 7 gives a rest of %remainder%
    )