Getting a random number divisible by 16

In mathematics, how to get the closest number to a number that is divisible by 16?

For example, I get a random number 100, and I want to rotate this number (using a mathematical function) to the nearest number to 100, which is divisible by 16 (in this case its 96)

I am trying to do this in JavaScript, but if I knew the mathematical formula for this, I would easily do it in any language.

Thanks, Relationship

+6
javascript
source share
6 answers
function GetRandomNumberBetween(lo, hi) { return Math.floor(lo + Math.random() * (hi - lo)); } Number.prototype.FindClosestNumberThatIsDivisibleBy = function(n) { return Math.round(this / n) * n; //simplify as per Guffa /* originally: var c = Math.ceil(n); var f = Math.floor(n); var m = num % n; var r = f * n; if (m > (n / 2)) r = c * n; return r; */ }; var r = GetRandomNumberBetween(10, 100); var c = r.FindClosestNumberThatIsDivisibleBy(16); 
+5
source share

Create a random integer. Multiply it by 16.

+18
source share

Divide by 16, round and multiply by 16:

 n = Math.round(n / 16) * 16; 
+14
source share
 function closest(n) { var r = 0, ans = 0; r = n % 16 if r < 8 { ans = n - r } else { ans = n + (16 - r) } return ans; } 
+3
source share

JS General Solution

 var divisor = 16; var lower = 0; var upper = 100; var randDivisible = (Math.floor(Math.random()*(upper-lower))+lower)*divisor; alert(randDivisible); 
+1
source share

This is how I understand your question. You are given the number A, and you need to find the number B, which is the closest multiple from 16 to A.

  • Take the indicated number, "A" and divide it by 16
  • Complete the answer from the previous step to the nearest integer
  • multiply the answer from the previous step by 16

there is pseudo code, hope what you are looking for; -)

+1
source share

All Articles