I was wondering how JavaScript handles modulo. For example, what would JavaScript evaluate 47 % 8 as? I can’t seem to find any documentation on it, and my skills on modulo aren’t the best.
Exactly as every language handles modulo: The remainder of X / Y.
47 % 8 == 7
Also if you use a browser like Firefox + Firebug, Safari, Chrome, or even IE8+ you could test such an operation as quickly as hitting F12.
Javascript's modulo operator returns a negative number when given a negative number as input (on the left side).
14 % 5 // 4
15 % 5 // 0
-15 % 5 // -0
-14 % 5 // -4
(Note: negative zero is a distinct value in JavaScript and other languages with IEEE floats, but -0 === 0 so you usually don't have to worry about it.)
If you want a number that is always between 0 and a positive number that you specify, you can define a function like so:
function mod(n, m) {
return ((n % m) + m) % m;
}
mod(14, 5) // 4
mod(15, 5) // 4
mod(-15, 5) // 0
mod(-14, 5) // 1
Modulo should behave like you expect. I expect.
47 % 8 == 7
Fiddle Link
TO better understand modulo here is how its built;
function modulo(num1, num2) {
if (typeof num1 != "number" || typeof num2 != "number"){
return NaN
}
var num1isneg=false
if (num1.toString().includes("-")){
num1isneg=true
}
num1=parseFloat(num1.toString().replace("-",""))
var leftover =parseFloat( ( parseFloat(num1/num2) - parseInt(num1/num2)) *num2)
console.log(leftover)
if (num1isneg){
var z = leftover.toString().split("")
z= ["-", ...z]
leftover = parseFloat(z.join(""))
}
return leftover
}
Related
Is there a more effective way to return true if n is a power of two or false if not?
function isPowerOfTwo(n) {
return Math.pow(2, Math.round(Math.log(n) / Math.log(2)));
}
You can actually use ECMAScript5 Math.log:
function powerOfTwo(x) {
return (Math.log(x)/Math.log(2)) % 1 === 0;
}
Remember, in math, to get a logarithm with an arbitrary base, you can just divide log10 of the operand (x in this case) by log10 of the base. And then to see if the number is a regular integer (and not a floating point), just check if the remainder is 0 by using the modulus % operator.
In ECMAScript6 you can do something like this:
function powerOfTwo(x) {
return Math.log2(x) % 1 === 0;
}
See the MDN docs for Math.log2.
Source: Bit twiddling Hacks,
function powerOf2(v) {
return v && !(v & (v - 1));
}
You just bitwise AND the previous number with the current number. If the result is falsy, then it is a power of 2.
The explanation is in this answer.
Note:
This will not be 100% true for programming, mathematical, [also read 'interviewing']. Some edge cases not handled by this are decimals (0.1, 0.2, 0.8…) or zero values (0, 0.0, …)
Using bitwise operators, this is by far the best way in terms of efficiency and cleanliness of your code:
function PowerofTwo(n){
return ((x != 0) && !(x & (x - 1)));
}
what it does is checks the bits that make up the number, i.e. 8 looks like this:
1 0 0 0
x-1 or 7 in this case looks like this
0 1 1 1
when the bitwise operator & is used it invokes an && on each bit of the number (thus 1 & 1 = 1, 1 & 0 = 0, 0 & 1 = 0, 0 & 0 = 1):
1 0 0 0
-0 1 1 1
=========
0 0 0 0
since the number turns into an exact 0 (or false when evaluted as a boolean) using the ! flag will return the correct answer
if you were to do this with a number like 7 it would look like this:
0 1 1 1
-0 1 1 0
=========
1 1 1 0
returning a number greater than zero causing the ! flag to take over and give the correct answer.
A number is a power of 2 if and only if log base 2 of that number is whole. The function below computes whether or not that is true:
function powerOfTwo(n){
// Compute log base 2 of n using a quotient of natural logs
var log_n = Math.log(n)/Math.log(2);
// Round off any decimal component
var log_n_floor = Math.floor(log_n);
// The function returns true if and only if log_n is a whole number
return log_n - log_n_floor == 0;
}
Making use of ES6's Math.clz32(n) to count leading zeros of a 32-bit integer from 1 to 2³² - 1:
function isPowerOf2(n) {
return Math.clz32(n) < Math.clz32(n - 1);
}
/**
* #param {number} n
* #return {boolean}
*/
const isPowerOfTwo = function(n) {
if(n == 0) return false;
while(n % 2 == 0){
n = n/2
}
return n === 1
};
function PowerOfTwo(n){
// Exercise for reader: confirm that n is an integer
return (n !== 0) && (n & (n - 1)) === 0;
}
console.log(PowerOfTwo(3))
console.log(PowerOfTwo(4))
This is for a specific online course that requires an answer in a specific way.
Without using libraries and other methods just loops and .push.
you need to create an inner loop using while
it should start with 1
keep multiplying it with 2 until i,j,k or whatever is greater than the current number(array) so it will have to do 2 4 6 8 10 12 14 16 18 until it is greater than the number
then it will go to the outer loop then repeat again until
const numbers = [5, 3, 9, 30];
const smallestPowerOfTwo = arr => {
let results = new Array;
// The 'outer' for loop -
for (let i = 0; i < arr.length; i++) {
number = arr[i];
// The 'inner' while loop
j = 1;
while (j < number) { //starting from 1 then multiplied by 2 then by 2 again untill it is more than the number
j = j * 2;
}
results.push(j);
}
return results
}
console.log(smallestPowerOfTwo(numbers))
According to Google Calculator (-13) % 64 is 51.
According to Javascript (see this JSBin) it is -13.
How do I fix this?
Number.prototype.mod = function (n) {
"use strict";
return ((this % n) + n) % n;
};
Taken from this article: The JavaScript Modulo Bug
Using Number.prototype is SLOW, because each time you use the prototype method your number is wrapped in an Object. Instead of this:
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
Use:
function mod(n, m) {
return ((n % m) + m) % m;
}
See: https://jsperf.app/negative-modulo/2
~97% faster than using prototype. If performance is of importance to you of course..
The % operator in JavaScript is the remainder operator, not the modulo operator (the main difference being in how negative numbers are treated):
-1 % 8 // -1, not 7
A "mod" function to return a positive result.
var mod = function (n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
mod(5,22) // 5
mod(25,22) // 3
mod(-1,22) // 21
mod(-2,22) // 20
mod(0,22) // 0
mod(-1,22) // 21
mod(-21,22) // 1
And of course
mod(-13,64) // 51
The accepted answer makes me a little nervous because it re-uses the % operator. What if Javascript changes the behavior in the future?
Here is a workaround that does not re-use %:
function mod(a, n) {
return a - (n * Math.floor(a/n));
}
mod(1,64); // 1
mod(63,64); // 63
mod(64,64); // 0
mod(65,64); // 1
mod(0,64); // 0
mod(-1,64); // 63
mod(-13,64); // 51
mod(-63,64); // 1
mod(-64,64); // 0
mod(-65,64); // 63
If x is an integer and n is a power of 2, you can use x & (n - 1) instead of x % n.
> -13 & (64 - 1)
51
Fix negative modulo (reminder operator %)
Simplified using ES6 Arrow function, and without dangerously extending the Number prototype
const mod = (n, m) => (n % m + m) % m;
console.log(mod(-90, 360)); // 270 (Instead of -90)
Though it isn't behaving as you expected, it doesn't mean that JavaScript is not 'behaving'. It is a choice JavaScript made for its modulo calculation. Because, by definition either answer makes sense.
See this from Wikipedia. You can see on the right how different languages chose the result's sign.
This is not a bug, there's 3 functions to calculate modulo, you can use the one which fit your needs (I would recommend to use Euclidean function)
Truncating the decimal part function
console.log( 41 % 7 ); // 6
console.log( -41 % 7 ); // -6
console.log( -41 % -7 ); // -6
console.log( 41 % -7 ); // 6
Integer part function
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // -6
console.log( parseInt( 41).mod(-7) ); // -1
Euclidean function
Number.prototype.mod = function(n) {
var m = ((this%n)+n)%n;
return m < 0 ? m + Math.abs(n) : m;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // 1
console.log( parseInt( 41).mod(-7) ); // 6
So it seems that if you're trying to mod around degrees (so that if you have -50 degrees - 200 degrees), you'd want to use something like:
function modrad(m) {
return ((((180+m) % 360) + 360) % 360)-180;
}
I deal with négative a and negative n too
//best perf, hard to read
function modul3(a,n){
r = a/n | 0 ;
if(a < 0){
r += n < 0 ? 1 : -1
}
return a - n * r
}
// shorter code
function modul(a,n){
return a%n + (a < 0 && Math.abs(n));
}
//beetween perf and small code
function modul(a,n){
return a - n * Math[n > 0 ? 'floor' : 'ceil'](a/n);
}
There is a NPM package that will do the work for you. You can install it with the following command.
npm install just-modulo --save
Usage copied from the README
import modulo from 'just-modulo';
modulo(7, 5); // 2
modulo(17, 23); // 17
modulo(16.2, 3.8); // 17
modulo(5.8, 3.4); //2.4
modulo(4, 0); // 4
modulo(-7, 5); // 3
modulo(-2, 15); // 13
modulo(-5.8, 3.4); // 1
modulo(12, -1); // NaN
modulo(-3, -8); // NaN
modulo(12, 'apple'); // NaN
modulo('bee', 9); // NaN
modulo(null, undefined); // NaN
GitHub repository can be found via the following link:
https://github.com/angus-c/just/tree/master/packages/number-modulo
For fun, here's a "wrap" function that works sorta like a modulo, except you can also specify the minimum value of the range (instead of it being 0):
const wrap = (value = 0, min = 0, max = 10) =>
((((value - min) % (max - min)) + (max - min)) % (max - min)) + min;
Basically just takes the true modulo formula, offsets it such that min ends up at 0, then adds min back in after.
Useful if you have a value that you want to keep between two values.
What does the % do in JavaScript?
A definition of what it is and what it does would be much appreciated.
It's a modulo operator. See this documentation or the specification for more information on JavaScript arithmetic operators.
% (Modulus)
The modulus operator is used as follows:
var1 % var2
The modulus operator returns the first operand modulo the second
operand, that is, var1 modulo var2, in the preceding statement, where
var1 and var2 are variables. The modulo function is the integer
remainder of dividing var1 by var2. For example, 12 % 5 returns 2. The
result will have the same sign as var1; that is, −1 % 2 returns −1.
ES6 Update:
As explained in other answers, it returns the remainder after dividing the dividend by divisor, however this is no longer modulo operator, this is remainder operator. the difference being that the modulo operator result would take the sign of the divisor, not the dividend.Quoted from MDN
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor. It uses a built-in modulo function to produce the result, which is the integer remainder of dividing var1 by var2 — for example — var1 modulo var2. There is a proposal to get an actual modulo operator in a future version of ECMAScript, the difference being that the modulo operator result would take the sign of the divisor, not the dividend.
Example:
-10 % 3 // -1
10 % -3 // 1
It returns the remainder of a division operation. 5%2 returns 1
It is a modulo operator.
It calculates the remainder.
If we do 23 % 10,
first, we divide 23 by 10 which equals 2.3
then take .3 * (the divisor) 10
= 3
That would be the modulo operator.
It returns the remainder of a division operation:
var remainder = 3 % 2; // equals 1
In JavaScript, % is a remainder operator (Not a modulo operator).
remainder operator % (uses Math.truc()):
remainder = -5 % 3 = -2
How is it calculated ?
quotient = Math.trunc(dividend / divisor) = Math.trunc(-5 / 3) = -1;
remainder = dividend - divisor * quotient = -5 - (3 * -1) = -2
modulo function (uses Math.floor()):
modulo(-5,3) = 1
How is it calculated ?
quotient = Math.floor(dividend / divisor) = Math.floor(-5 / 3) = -2;
remainder = dividend - divisor * quotient = -5 - (3 * -2) = 1
For positive numbers, both remainder operator and modulo gives the same result.
5 % 3 = 2
modulo(5,3) = 2
In JavaScript, there is no build-in function for doing modulo operation, so you need to write on your own by using Math.floor() as above. Alternatively even you could easily write using the remainder operator as shown below.
function modulo(n, m) {
return ((n % m) + m) % m;
}
Just in case, if someone is looking for a real modulo function (which would always get the sign of the divisor), you can use this:
function Modulo(num, denom)
{
if (num%denom >= 0)
{
return Math.abs(num%denom);
}
else
{
return num%denom + denom;
}
}
The Math.abs is to prevent the case -12%12 → -0, which is considered equal to 0 but displayed as -0.
Modulus (%) operator returns the remainder.
If either value is a string, an attempt is made to convert the string to a number.
alert(5%3) will alert 2
% performs as the modulo operator, return division reminder. Example:
<script>
var x = 5;
var y = 2;
var z = x % y;
alert(z);
</script>
This will alert 1.
This is what I would do to getModulus, given k > 0. I find it more intuitive as Math.floor(num / k ) in js is exactly num // k in python.
function getModulus(num, k) {
return num - Math.floor(num / k ) * k
}
According to Google Calculator (-13) % 64 is 51.
According to Javascript (see this JSBin) it is -13.
How do I fix this?
Number.prototype.mod = function (n) {
"use strict";
return ((this % n) + n) % n;
};
Taken from this article: The JavaScript Modulo Bug
Using Number.prototype is SLOW, because each time you use the prototype method your number is wrapped in an Object. Instead of this:
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
Use:
function mod(n, m) {
return ((n % m) + m) % m;
}
See: https://jsperf.app/negative-modulo/2
~97% faster than using prototype. If performance is of importance to you of course..
The % operator in JavaScript is the remainder operator, not the modulo operator (the main difference being in how negative numbers are treated):
-1 % 8 // -1, not 7
A "mod" function to return a positive result.
var mod = function (n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
mod(5,22) // 5
mod(25,22) // 3
mod(-1,22) // 21
mod(-2,22) // 20
mod(0,22) // 0
mod(-1,22) // 21
mod(-21,22) // 1
And of course
mod(-13,64) // 51
The accepted answer makes me a little nervous because it re-uses the % operator. What if Javascript changes the behavior in the future?
Here is a workaround that does not re-use %:
function mod(a, n) {
return a - (n * Math.floor(a/n));
}
mod(1,64); // 1
mod(63,64); // 63
mod(64,64); // 0
mod(65,64); // 1
mod(0,64); // 0
mod(-1,64); // 63
mod(-13,64); // 51
mod(-63,64); // 1
mod(-64,64); // 0
mod(-65,64); // 63
If x is an integer and n is a power of 2, you can use x & (n - 1) instead of x % n.
> -13 & (64 - 1)
51
Fix negative modulo (reminder operator %)
Simplified using ES6 Arrow function, and without dangerously extending the Number prototype
const mod = (n, m) => (n % m + m) % m;
console.log(mod(-90, 360)); // 270 (Instead of -90)
Though it isn't behaving as you expected, it doesn't mean that JavaScript is not 'behaving'. It is a choice JavaScript made for its modulo calculation. Because, by definition either answer makes sense.
See this from Wikipedia. You can see on the right how different languages chose the result's sign.
This is not a bug, there's 3 functions to calculate modulo, you can use the one which fit your needs (I would recommend to use Euclidean function)
Truncating the decimal part function
console.log( 41 % 7 ); // 6
console.log( -41 % 7 ); // -6
console.log( -41 % -7 ); // -6
console.log( 41 % -7 ); // 6
Integer part function
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // -6
console.log( parseInt( 41).mod(-7) ); // -1
Euclidean function
Number.prototype.mod = function(n) {
var m = ((this%n)+n)%n;
return m < 0 ? m + Math.abs(n) : m;
};
console.log( parseInt( 41).mod( 7) ); // 6
console.log( parseInt(-41).mod( 7) ); // 1
console.log( parseInt(-41).mod(-7) ); // 1
console.log( parseInt( 41).mod(-7) ); // 6
So it seems that if you're trying to mod around degrees (so that if you have -50 degrees - 200 degrees), you'd want to use something like:
function modrad(m) {
return ((((180+m) % 360) + 360) % 360)-180;
}
I deal with négative a and negative n too
//best perf, hard to read
function modul3(a,n){
r = a/n | 0 ;
if(a < 0){
r += n < 0 ? 1 : -1
}
return a - n * r
}
// shorter code
function modul(a,n){
return a%n + (a < 0 && Math.abs(n));
}
//beetween perf and small code
function modul(a,n){
return a - n * Math[n > 0 ? 'floor' : 'ceil'](a/n);
}
There is a NPM package that will do the work for you. You can install it with the following command.
npm install just-modulo --save
Usage copied from the README
import modulo from 'just-modulo';
modulo(7, 5); // 2
modulo(17, 23); // 17
modulo(16.2, 3.8); // 17
modulo(5.8, 3.4); //2.4
modulo(4, 0); // 4
modulo(-7, 5); // 3
modulo(-2, 15); // 13
modulo(-5.8, 3.4); // 1
modulo(12, -1); // NaN
modulo(-3, -8); // NaN
modulo(12, 'apple'); // NaN
modulo('bee', 9); // NaN
modulo(null, undefined); // NaN
GitHub repository can be found via the following link:
https://github.com/angus-c/just/tree/master/packages/number-modulo
For fun, here's a "wrap" function that works sorta like a modulo, except you can also specify the minimum value of the range (instead of it being 0):
const wrap = (value = 0, min = 0, max = 10) =>
((((value - min) % (max - min)) + (max - min)) % (max - min)) + min;
Basically just takes the true modulo formula, offsets it such that min ends up at 0, then adds min back in after.
Useful if you have a value that you want to keep between two values.
how to convert -1 to 1 with javascript ?
var count = -1; //or any other number -2 -3 -4 -5 ...
or
var count = 1; //or any other number 2 3 4 5 ...
result should be
var count = 1; //or any other number 2 3 4 5 ...
count = Math.abs(count)
// will give you the positive value of any negative number
The abs function turns all numbers positive: i.e Math.abs( -1 ) = 1
Alternative approach (might be faster then Math.abs, untested):
count = -5;
alert((count ^ (count >> 31)) - (count >> 31));
Note that bitwise operations in javascript are always in 32-bit.
If the number of interest is input... In addition to Math.abs(input)....
var count = (input < 0 ? -input : input);
jsFiddle example
(edit: as Some pointed out -input is faster than -1 * input)
The above makes use of the Javascript conditional operator. This is the only ternary (taking three operands) Javascript operator.
The syntax is:
condition ? expr1 : expr2
If the condition is true, expr1 is evaluated, if it's fales expr2 is evaluated.