This question already has answers here:
How to round an integer up or down to the nearest 10 using Javascript
(4 answers)
Closed 6 years ago.
How can I round an integer number in Javascript to the nearest 10? My math is pretty rubbish today :)
Some sample cases:
45 = 50
41 = 50
40 = 40
I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.
Any help/pointers appreciated,
thanks
//Update: faster way
var getDozen = function (n) {
var r = n % 10;
// if its greater than 4
if (r > 4)
return n - r + 10;
//if its lower than 5, then subtract the remainder
else
return n - r;
}
console.log(getDozen(45)); // 50
var getDozen = function (n) {
var r = n % 10;
if (r > 4) return Math.ceil(n / 10) * 10;
else return Math.floor(n / 10) * 10;
}
console.log(getDozen(45)); // 50
Related
const reversedNum = num =>
parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
console.log(reversedNum(456))
Couldn't figure it out how to write code in order to sum 654 + 456
Thank You very much!
const reversedNum = num => num + +num.toString().split('').reverse().join('')
You can return sum of num and reversedNum inside a function.
const sumOfNumAndReversedNum= num => {
const reversedNum = parseFloat(num.toString().split('').reverse().join('')) * Math.sign(num)
return num + reversedNum
}
let userNumber = 456
console.log(sumOfNumAndReversedNum(userNumber))
You can write a more performant way of reversing the number than turning it into a string, flipping it, and turning it back into an integer.
One option is to go through the number backwards by popping off the last integer (e.g., 123 % 10 === 3) and adding it to your newly reversed number. You'll also need to multiply your reversed number by 10 in each iteration to move you to the next degree.
For example, given the number 123:
123 % 10 = 3;
123 /= 10 = 12;
0 * 10 + 3 = 3;
1 % 10 = 2;
12 /= 10 = 1;
3 * 10 + 2 = 32
1 % 10 = 1;
1 /= 10 = 0;
32 * 10 + 1 = 321
This method will also automatically take care of negative numbers for you, leaving you something like:
function reverse(num) {
let reversed = 0;
while (num !== 0) {
const popped = num % 10;
num = parseInt(num / 10);
if (reversed > Number.MAX_VALUE / 10 || (reversed === Number.MAX_VALUE / 10 && popped > 7)) return 0;
if (reversed < Number.MIN_VALUE / 10 || (reversed === Number.MIN_VALUE / 10 && popped < -8)) return 0;
reversed = reversed * 10 + popped;
}
return reversed;
}
Now you can simply call:
console.log(123 + reverse(123))
const reversedNum = num =>
Number(num.toString().split('').reverse().join(''))
console.log(reversedNum(456))
Do it!
This question already has answers here:
Round number up to the nearest multiple of 3
(13 answers)
Closed 1 year ago.
I have a math problem like this:
When I enter a number, I find the nearest larger number that is divisible by a number x
Example: x = 50
Input = 20 => output = 50
Input = 67 => output = 100
Input = 200 => output = 200
Input = 289 => output = 300
Input = 999 => output = 1000
.......
I have a function below, but is there a way to make it faster?
console.log(roundNumber(199));
function roundNumber(n) {
let x = 50;
let flg = false;
while (flg === false) {
if (n > x) {
x += 50;
} else {
flg = true;
}
}
return x;
}
Yes, you can divide the input value by 50, take the "floor", add 1, and then multiply by 50.
function roundNumber(n) {
let x = 50;
return (Math.floor((n + x - 1) / x)) * 50;
}
Whether this will be much faster is kind-of irrelevant, unless for some reason you're performing this operation thousands and thousands of times over a short interval.
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));
This question already has answers here:
Rounding to nearest 100
(7 answers)
Closed 9 years ago.
I'm trying to round a number the 100.
Example:
1340 should become 1400
1301 should become 1400
and
298 should become 300
200 should stay 200
I know about Math.round but it doesn't round to the 100.
How can I do that ?
Original Answer
Use the Math.ceil function, such as:
var result = 100 * Math.ceil(value / 100);
Generalised Version
This function can be generalised as follows:
Number.prototype.roundToNearest = function (multiple, roundingFunction) {
// Use normal rounding by default
roundingFunction = roundingFunction || Math.round;
return roundingFunction(this / multiple) * multiple;
}
Then you can use this function as follows:
var value1 = 8.5;
var value2 = 0.1;
console.log(value1.roundToNearest(5)); // Returns 10
console.log(value1.roundToNearest(5, Math.floor)); // Returns 5
console.log(value2.roundToNearest(2, Math.ceil)); // Returns 2
Or with a custom rounding function (such as banker's rounding):
var value1 = 2.5;
var value2 = 7.5;
var bankersRounding = function (value) {
var intVal = Math.floor(value);
var floatVal = value % 1;
if (floatVal !== 0.5) {
return Math.round(value);
} else {
if (intVal % 2 == 0) {
return intVal;
} else {
return intVal + 1;
}
}
}
console.log(value1.roundToNearest(5, bankersRounding)); // Returns 0
console.log(value2.roundToNearest(5, bankersRounding)); // Returns 10
An example of the code running is available here.
Try this...
function roundUp(value) {
return (~~((value + 99) / 100) * 100);
}
That will round up to the next hundred - 101 will return 200.
jsFiddle example - http://jsfiddle.net/johncmolyneux/r8ryd/
Open your console to see the results.
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);