开发者

Getting random number divisible by 16

In math how do I obtain the closest number of a number that is divisible by 16?

For example I get the random number 100 and I want to t开发者_如何学Gourn that number (using a math function) into the closest number to 100 that is divisible by 16 (In this case its 96)

I'm trying to do this in JavaScript but if I knew the math formula for it I would easily do it in any language.

Thank you, Regards


Generate a random integer. Multiply it by 16.


Divide by 16, round, and multiply by 16:

n = Math.round(n / 16) * 16;


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


function closest(n) {
  var r = 0, ans = 0;

  r = n % 16

  if r < 8 {
    ans = n - r
  } else {
    ans = n + (16 - r)
  }

  return ans;
}


Here's how I understand your question. You're given a number A, and you have to find a number B that is the closest possible multiple of 16 to A.

  1. Take the number given, "A" and divide it by 16
  2. Round the answer from previous step to the nearest whole number
  3. multiply the answer from previous step by 16

there's the pseudocode, hope it's what you're looking for ;-)


A general JS solution

var divisor = 16;

var lower = 0;
var upper = 100;    

var randDivisible = (Math.floor(Math.random()*(upper-lower))+lower)*divisor;
alert(randDivisible);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜