Getting random number divisible by 16 - javascript

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 turn 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.
Take the number given, "A" and divide it by 16
Round the answer from previous step to the nearest whole number
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);

Related

Diffie Hellman Key Exhange not working (Javascript)

I tried to create the Diffie Hellman key exchange system in javascript without plugins. My code unfortunately doesn't work and often creates 2 different secret keys.
Code:
var g = next_Prime_num(Math.ceil(Math.random() * 50));
var n = next_Prime_num(Math.ceil(Math.random() * 50) + 50);
var a = Math.ceil(Math.random() * (n - 1));
var b = Math.ceil(Math.random() * (n - 1));
var A = mod(Math.pow(g, a), n);
var B = mod(Math.pow(g, b), n);
var Ka = mod(Math.pow(B, a), n);
var Kb = mod(Math.pow(A, b), n);
function next_Prime_num(num) {
for (var i = num + 1;; i++) {
var isPrime = true;
for (var d = 2; d * d <= i; d++) {
if (i % d === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
return i;
}
}
}
function mod(n, m) {
return n%m;
}
n: must be a prime number yes, but
g: must be a primitive root of n, and not a just prime number
this is your mistake, you have to add another function to get a primitive root from the givin prim number
The Math.pow() in there is definitely going to have integer overflows every now and then. In javascript the maximum integer you can have without loosing precision or maximum safe integer is (253 - 1) or 9007199254740991 .
What you can do is create a power function which uses modular exponentiation.
Check out this similar question - Diffie-Hellman Key Exchange with Javascript sometimes wrong

Round to the nearest factor of N

Given a number, x (like 13), and a factor N (like 2), how can I compute the values 8 and 16 below?
8 <= 13 < 16
In other words, how can I compute the two ends of the equality here:
N^? <= x < N^(? + 1)
You could take the floored nth logarithm of the number and use it as value for getting the power of f and f plus one.
function getInterval(x, n) {
var f = Math.floor(Math.log(x) / Math.log(n));
return [Math.pow(n, f), Math.pow(n, f + 1)];
}
console.log(getInterval(3, 2).join(' '));
console.log(getInterval(23, 7).join(' '));
console.log(getInterval(13, 2).join(' '));
Edit. Question sense was completely changed.
pwr = Math.floor(Math.log(x) / Math.log(n))
low = Math.pow(n, pwr)
high = Math.pow(n, pwr + 1)

Optimising Javascript

I was given a quiz and I had gotten the answer wrong and It's been bugging me ever since so I thought I'd ask for your thoughts
I needed to optimise the following function
function sumOfEvenNumbers(n) {
var sum = 0;
for(let i = 2; i < n;i++){
if(i % 2 == 0) sum += i;
}
return sum;
}
console.log(sumOfEvenNumbers(5));
I came up with
function sumOfEvenNumbers(n) {
var sum = 0;
while(--n >= 2) sum += n % 2 == 0? n : 0
return sum;
}
console.log(sumOfEvenNumbers(5));
What other ways were there?
It's a bit of a math question. The sum appears to be the sum of an arithmitic sequence with a common difference of 2. The sum is:
sum = N * (last + first) / 2;
where N is the number of the numbers in the sequence, last is the last number of those numbers, and first is the first.
Translated to javascript as:
function sumOfEvenNumbers(n) {
return Math.floor(n / 2) * (n - n % 2 + 2) / 2;
}
Because the number of even numbers between 2 and n is Math.floor(n / 2) and the last even number is n - n % 2 (7 would be 7 - 7 % 2 === 6 and 8 would be 8 - 8 % 2 === 8). and the first is 2.
Sum of n numbers:
var sum = (n * (n+1)) / 2;
Sum of n even numbers:
var m = Math.floor(n/2);
var sum = 2 * (m * (m+1) /2);
You can compute these sums using an arithmetic sum formula in constant time:
// Return sum of positive even numbers < n:
function sumOfEvenNumbers(n) {
n = (n - 1) >> 1;
return n * (n + 1);
}
// Example:
console.log(sumOfEvenNumbers(5));
Above computation avoids modulo and division operators which consume more CPU cycles than multiplication, addition and bit-shifting. Pay attention to the limited range of the bit-shifting operator >> though.
See e.g. http://oeis.org/A002378 for this and other formulas leading to the same result.
First thing is to eliminate the test in the loop:
function sumOfEvenNumbers(n) {
var sum = 0;
var halfN= Math.floor(n/2);
for(let i = 1; i < n/2;i++) {
sum += i;
}
return sum * 2;
}
Then we can observe that is just calculating the sum of all the integers less than a limit - and there is a formula for that (but actually formula is for less-equal a limit).
function sumOfEvenNumbers(n) {
var halfNm1= Math.floor(n/2)-1;
var sum = halfNm1 * (halfNm1+1) / 2;
return sum * 2;
}
And then eliminate the division and multiplication and the unnecessary addition and subtraction:
function sumOfEvenNumbers(n) {
var halfN= Math.floor(n/2);
return (halfN-1) * halfN;
}
Your solution computes in linear (O(N)) time.
If you use a mathematical solution, you can compute it in O(1) time:
function sum(n) {
let half = Math.ceil(n/2)
return half * (half + 1)
}
Because the question is tagged ecmascript-6 :)
const sumEven = x => [...Array(x + 1).keys()].reduce((a, b) => b % 2 === 0 ? a + b : a, 0);
// set max number
console.log(sumEven(10));

Sum all numbers between two integers

OBJECTIVE
Given two numbers in an array, sum all the numbers including (and between) both integers (e.g [4,2] -> 2 + 3 + 4 = 9).
I've managed to solve the question but was wondering if there is a more elegant solution (especially using Math.max and Math.min) - see below for more questions...
MY SOLUTION
//arrange array for lowest to highest number
function order(min,max) {
return min - max;
}
function sumAll(arr) {
var list = arr.sort(order);
var a = list[0]; //smallest number
var b = list[1]; //largest number
var c = 0;
while (a <= b) {
c = c + a; //add c to itself
a += 1; // increment a by one each time
}
return c;
}
sumAll([10, 5]);
MY QUESTION(S)
Is there a more efficient way to do this?
How would I use Math.max() and Math.min() for an array?
Optimum algorithm
function sumAll(min, max) {
return ((max-min)+1) * (min + max) / 2;
}
var array = [4, 2];
var max = Math.max.apply(Math, array); // 4
var min = Math.min.apply(Math, array); // 2
function sumSeries (smallest, largest) {
// The formulate to sum a series of integers is
// n * (max + min) / 2, where n is the length of the series.
var n = (largest - smallest + 1);
var sum = n * (smallest + largest) / 2; // note integer division
return sum;
}
var sum = sumSeries(min, max);
console.log(sum);
The sum of the first n integers (1 to n, inclusive) is given by the formula n(n+1)/2. This is also the nth triangular number.
S1 = 1 + 2 + ... + (a-1) + a + (a+1) + ... + (b-1) + b
= b(b+1)/2
S2 = 1 + 2 + ... + (a-1)
= (a-1)a/2
S1 - S2 = a + (a+1) + ... + (b-1) + b
= (b(b+1)-a(a-1))/2
Now we have a general formula for calculating the sum. This will be much more efficient if we are summing a large range (e.g. 1 million to 2 million).
Here is a one liner recursive program solution of SumAll using es6.
const SumAll = (num, sum = 0) => num - 1 > 0 ? SumAll(num-1,sum += num) : sum+num;
console.log(SumAll(10));
Note :: Although the best Example is using the Algorithm, as mentioned above.
However if the above can be improved.

Polyline Length

I get line length by this functions.
google.maps.LatLng.prototype.kmTo = function(a){
var e = Math, ra = e.PI/180;
var b = this.lat() * ra, c = a.lat() * ra, d = b - c;
var g = this.lng() * ra - a.lng() * ra;
var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos
(c) * e.pow(e.sin(g/2), 2)));
return f * 6378.137;
}
google.maps.Polyline.prototype.inKm = function(n){
var a = this.getPath(n), len = a.getLength(), dist = 0;
for (var i=0; i < len-1; i++) {
dist += a.getAt(i).kmTo(a.getAt(i+1));
}
return dist;
}
And use :
alert('Line Length: '+ poly1.inKm() +'');
Everything working. But i have a small problem.
Its shows me: >> Line Length: 8.854502612255438km <<
Digits is to long i want it show me only 8.8 how can i do it?
Sorry for my english!
Try something like:
Math.floor(x * 10) / 10
Where x is the number you are trying to show (8.854502612255438).
Instead of floor (which will turn 88.5 to 88) you may want to try round (which will turn 88.5 to 89).
Edit - ah no, that won't work will it because your number is a string with 'km' at the end (did not spot that)...
so... try using parseFloat like this:
Math.floor(parseFloat(x, 10) * 10) / 10
You would have to add 'km' to the end of the string your self, so the full thing becomes:
alert('Line Length: '+ (Math.floor(parseFloat(poly1.inKm(), 10) * 10) / 10) +'km');

Categories