Why is JavaScript modulus (%) operator not working as expected? - javascript

I am writing a small program which takes as input an integer N and returns true if it is a power of 3. Otherwise, false.
While there are many ways to write such a program, I am particularly interested in ** only ** making following solution work.
First, I find max integer value supported by JavaScript i.e. Number.MAX_VALUE
Then, using this I get max interger value divisible by 3 using formula: Math.floor(Math.log(Number.MAX_VALUE) / Math.log(3)). This comes out to be 646.
So far so good.
Now, idea is that if 3^646 mod N == 0, then N is a power of 3 because 3 is a prime number.
This works perfectly fine on Wolfram Alpha (e.g. http://m.wolframalpha.com/input/?i=%283%5E646%29+mod+27).
Problem:
But I don't get zero when I do the same using JavaScript i.e. Math.pow(3, 646) % 27 returns 5, instead of 0.
Isn't % the modulus operator I am suppose to use?
Am I missing something here?
Thanks :)

Related

Write a function that returns the square of a number without using *,+ or pow

The task is to write a function that takes n as an input where n is a number (from -32768 to 32768) and returns the square of that number. Simple task except for the fact that we cannot use any operators such as *,+ or even use any Math. functions such as pow. eval is not allowed as well.
Even more challenging is that we must keep the character code count less than 39 characters.
I absolutely cannot think of a way to get the square of a number without using the + or *. And even worse, to keep the character count less, it's impossible for me.
Codes like this won't work because: I used the plus sign and the character count is more than 60.
function sq(n){
var res=n;
for(i=1;i<n;i++)
res+=n;
return res;
}
If n is a decimal, we are expected to return the nearest whole number as the result.
Thank you for reading all of this!
Edit: My problem has been solved. Thank you to everyone who has tried to help me with their codes as it helped me gain a new aspect of solving each problems.
Thank you very much again!
You can try this as well
function multiply(a) {
return a / (1 / a);
}
console.log(multiply(6))
console.log(multiply(4))
The repeat() method returns a new string with a specified number of copies of the string it was called on. See here
This approach is limited to positive and integer numbers only.
// Another method
function multiplytwo(a) {
return ("i").repeat(a).repeat(a).length
}
console.log(multiplytwo(4))
console.log(multiplytwo(25))
//creating a string “i” and repeating it “a” times, then repeats that “a” times, and then returning the length.
You could divide n by 1 / n
For rounding off without using Math.round, I have used this:
s=n=>(r=>(r-~~r<.5?0:1)- -~~r)(n/(1/n))
console.log(s(5));
console.log(s(4.4));
console.log(s(-4.44));
This has 39 characters.
** is not in your list, so you might be able to use it:
sq = n => n ** 2
console.log(sq(5));
You could also use - twice, instead of +:
sq=n=>{s=0;for(let i=n;i>0;i--)s=s-(-n);return s}
console.log(sq(5));
(function definition is 49 characters)
If anyone still needs a solution that passes tests.
#adiga's solution works nicely. But if you need to be under 39 characters you can exploit JS implicit type coercion: substitute r-~~r<.5?0:1 by r-~~r<.5. It will give you a boolean which will be coerced to either 1 or 0. So, final solution is following:
s=n=>(r=>(r-~~r<.5)- -~~r)(n/(1/n))
As this just got brought back up, here is a 22-character solution:
sq=n=>~~-(-.5-n/(1/n))
;[[0, 0], [1, 1], [2, 4], [3, 9], [4.4, 19], [-4.44, 20], [32768, 1073741824]]
.forEach (([n, s]) => console .log (`sq(${n}) == ${s} //=> ${sq(n) == s}`))
Explanation
Like other answers here it takes advantage of the fact that n / (1/n) is mathematically equivalent to squaring n. This is also helped by the fact that although 1 / 0 is Infinity, 0 / Infinity gives back 0. Mathematically this is iffy, but for the problem it's perfect. The trick is then to round this to the nearest integer. We could do so like this:
let sq = (n) => Math .round(n / (1 /n) + 0.5)
But we have two issues here. First we take the fact that Math.round is disallowed by the rules. Here we can use a common substitution for Math.round, namely ~~. This is simply two consecutive applications of the bitwise NOT operator, which first removes any fractional part to convert the result to a 32-bit integer, then inverts all the bits. Doing it a second time acts much like integer truncation, giving something more like:
let sq = (n) => ~~ (n / (1 /n) + 0.5)
But we still have a + in the definition, also disallowed. But that can be replaced by subtracting the negation of the value, with a version like this:
let sq = (n) => ~~ (n / (1 /n) - -0.5)
Now, minifying this would give us
sq=(n)=>~~(n/(1/n)- -.5)
and this is an equivalent 22-character solution. But for some reason I really didn't like the space in that version, and since (a - b) is equivalent to - (b - a), we can create this alternative:
let sq=n=>~~-(-.5-n/(1/n))
I'm not generally much of a code-golfer. I simply don't see the point. But this was a fun little challenge.

Incremental Correctness Recursive Algorithm in JavaScript

The pseudocode for incrementing natural numbers using a recursive algorithm is like this (example from the Algorithm Design Manual by Steven S. Skiena):
Increment(y)
if y = 0 then return(1) else
if (y mod 2) = 1 then
return(2 * Increment(y/2))
else return(y + 1)
I implemented it with JavaScript here: https://repl.it/#danielmai/IncrementalNaturalNumbers
function increment(y) {
if(y == 0) return 1
if(y % 2 == 1) {
return 2 * increment(y / 2)
}
else return y + 1
}
It doesn't work for odd numbers. I found out that JavaScript rounds up numbers with 0.5 or higher, so if y is odd, it will increment twice, i.e 5 -> 7.
I can use Math.floor(y/2) to make it round down, but I assume this function should work regardless of rounding up or down. So my question is, is there a way to correct this recursive function in JS without using Math.floor?
This has nothing to do with javascript rounding numbers up with 0.5 or higher.
Your increment function is asuming x / 2 will return an integer, but in javascript this will give a decimal number when odd. So when doing increment(3), you are recursively calling increment(1.5). As 1.5 % 2 = 1.5, its not == 1 so it ends up returning 2.5. So in the end, you end up returning 2.5 * 2 = 5.
This funcion would indeed work on c++ where if you are working with integers, division will trim trailing decimals. However, in javascript addition +, subtraction -, multiplication *, division /, power **, and modulo % all treat numbers in JavaScript as a double. Only binary operators treat numbers in JavaScript as a signed 32 bit integer.
Javascript doesn't have integer division, so you can't just do 5/2 and expect it to give you 2.
If you're looking for an alternative to Math.floor, this website has you covered. It has all of the alternatives you could ever want, and can check which will be the fastest on your browser.

Result of -1%7 is different in javascript(-1) and python(6)

The expression -1 % 7 in JavaScript is giving me -1 as the result. Whereas in Python and Haskell, I found the result to be 6.
Can anyone explain why both have different behaviors? Which one is correct?
I'm going to give a slightly different answer. As others have said, functions can do whatever you define them to and m - x = -x mod m. As a prelude, I'll note that Haskell has two "mod" functions, mod and rem which differ in just this aspect. You can make a case that the mod one is preferable mathematically. The rem one corresponds to what you'd get on an x86 processor. There is, in fact, a third one, the Euclidean one, which may be even better as well as described by Raymond Boute in The Euclidean Definitions of the Functions Div and Mod. The third form always returns a positive modulus. (There are, in fact, at least two other choices that can be made.)
So, Javascript's definition is what you get from most machine mod opcodes. In this sense, it might be preferable as this would make it more efficient to implement. Mathematically, Haskell's and Python's definition is better than Javascript's. There's also a third definition which may be slightly better.
One key property that the Euclidean and Haskell/Python definitions both possess is x mod m = y mod m is equivalent to x = y mod m which Javascript's definition lacks. You can verify by calculating 6 % 7 in Javascript.
Both are correct. Some languages return positive modulo numbers, while others retain their sign.
You can simply add the modulus to your variable to get a positive number, or check if the number is positive or negative before performing the modulus operation and correct the result after to switch between the two.
Pseudocode to convert a%b between the two:
In a language where -1%7 == -1, you do this to get a positive number:
((a%b)+b) % b
And in a language where -1%7 == 6 you can do this to get the signed version:
if a < 0:
return (a%b)-b
else:
return a%b
Both are correct, they just use different conventions regarding the handling of negative operands. For positive numbers, the conventions coincide, but for negative numbers they do not. In Python a % b always has the same sign as b.
In what follows, I'll use Python notation, where // is used for integer division.
Let
q, r = a // b, a % b
Then
a == q * b + r
must be true in any language (assuming a and b are integers, with b not equal to zero). So the way the remainder is handled has to be consistent with the convention used for integer division. In Python, integer division is floor division, i.e., the result is rounded towards negative infinity. In some other languages rounding towards zero is used instead. And in some languages, you get whatever convention the CPU manufacturer decided to implement, so the same code run on different hardware can give different results. As you can imagine, that can be somewhat annoying. :)
The % stands for different operators in JavaScript and in Python.
In JavaScript, the % stands for the Remainder operator. The documentation already points out the difference between the remainder and the modulo operation:
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.
(Emphasis by me)
In contrast to that: In Python, the % stands for the modulo operator. The documentation also makes a statement about the sign:
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. [...] The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
(Emphasis by me)
Both are correct.
To complete the other answers, you can also consider the divmod function in Python:
Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
>>> divmod(-1, 7)
(-1, 6)

Can anyone explain this process with converting decimal numbers to Binary

I have looked around the internet for a way to convert decimal numbers into binary numbers. and i found this piece of code in some forum.
var number = prompt("Type a number!") //Asks user to input a number
var converted = []; // creates an array with nothing in it
while(number>=1) { //While the number the user typed is over or equal to 1 its shoud loop
converted.unshift(number%2); // takes the "number" and see if you can divid it by 2 and if theres any rest it puts a "1" otherwise "0"
number = Math.floor(number/2); // Divides the number by 2, then starts over again
}
console.log(converted)
I'm not understanding everything completely, so i made some comments of what i think the pieces of code do. But anyone that can explain in more detail? or is the way i think the code does correct?
This code is based on a technique for converting decimal numbers to binary.
If I take a decimal number. I divide it by two and get the remainder which will either be 0 or 1. Once you divide 57 all the way down to 0. You get the binary number for example:
57 / 2 = 28 r 1; 28 / 2 = 14 r 0; 14 / 2 = 7 r 0; 7 / 2 = 3 r 1; 3 / 2 = 1 r 1; 1 / 2 = 0 r 1;
The remainders are the binary number. Sorry if it's a bit hard to read. I definitely recommend writing it out on paper. Read from the last remainder to the first, the remainders look like this: 111001
Reverse it to make it correct. array.unshift() can do this or you could use array.push() then array.reverse() after the while loop. Unshift() is probably a better approach.
57 in decimal is equal to 111001, which you can check.
BTW, this algorithm works for other bases, as long you are converting from decimal. Or at least as far as I know.
I hope this helped.
It seems like you've got the gist of it down.
Let's start with a random number:
6 === 110b
Now let's see what the above method does:
The number is geq than 1, hence, let's add the last bit of the number to the output
6%2 === 0 //output [0]
the number we're working with after dividing the number by two, which is essentially just bit-shifting the whole thing to the right is now 11b (from the original 110b). 11b === 3, as you'd expect.
You can alternatively think of number % 2 as a bit-wise AND operation (number & 1):
110
& 1
-----
0
The rest of the loop simply carries the same operation out as long as needed: find the last bit of the current state, add it to the output, shift the current state.

MDN example (of Math.random()): could it be parseInt() instead of Math.floor()?

I was reading a JavaScript tutorial and searching for functions on MDN website when I stumbled across this example of Math.random():
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
While I understand that Math.floor chooses the biggest number and with that erases all numbers that have decimal values, I already learnt another function called parseInt() which just deletes all of the numbers after point. So, what's the difference between those two? Couldn't I just use
function getRandomInclusive(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
}
instead?
I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4, but it's not really important for random number generator as I understand (if you know any examples of when it would be important, please tell me!) So, there's still not much of a difference in this case?
parseInt parses a string into an integer, reading only digits at the beginning of that string. It is not appropriate to use to round a number to an integer. The number will be converted to a string first, sometimes with unexpected results:
var num = 1000000000000000000000;
parseInt(num) // 1, because the string representation is 1e+21
I got idea while writing this question that Math.floor() might write 5 when it's 4,5 and parseInt() would write 4
You’re thinking of rounding to the nearest whole number, which is what Math.round does. Math.floor always rounds down.
The clear difference is that Math.floor is a function that works on numbers while parseInt is a function that takes a string. You don't want to use the latter here as we deal with random numbers.
If you are unsure about the rounding mode, compare Math.floor, Math.round and Math.ceil.
Here's an example where their behaviour differs drastically: negative numbers.
Math.floor(-2.5) -> -3
parseInt(-2.5) -> -2
The semantic difference pointed out in other answers, however, is probably more important. Even if it does work for your particular and specific use-case, it's best to pick the one with the correct semantics. (There are countless other ways to return a seemingly random integer from a function, you should pick the one that's the least likely to make your code hard to maintain.)

Categories