How does this equation gives random numbers between max and min divisible by divisibleBy

echo $(((RANDOM%(max-min+divisibleBy))/divisibleBy*divisibleBy+min))
  • 1
    Isn't this more of a question for math.stackexchange.com ? – Lucas May 17 '16 at 12:17
  • i dont know where to put it, it does seem like a math question either.I got it from advanced bash scripting guide.will just wait for a while untill i delete on of the two – munish May 17 '16 at 12:32

Think of it as working in steps of divsibleBy units times an integer.

ignoring the RANDOM for the moment, (max-min+divisbleBy)/divisibleBY would be the width of the range in plain integers, instead of (unit x integer), so (max-min+divisibleBy) is the width in (unit x integers)

the % is a modulo operator to give you a number inside the (unit x integer) width out of RANDOM (which will be between 0 and 32767 itself)

the /divisibleBy*divisibleBy part makes sure you are not getting a non-zero remainder when inside the set of (units x integers)

the +min shifts the random number (that falls within the width) back up into the target range

  • it was a brain twister for me – munish May 17 '16 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.