Javascript bitwise operation - javascript

I was doing a Leetcode problem for 231. Power of Two and one of the solution is to use Bitwise Operators to get the Rightmost 1-bit, here is the answer.
/**
* #param {number} n
* #return {boolean}
*/
var isPowerOfTwo = function(n) {
if (n === 0) return false;
const x = n;
return (x & (-x)) === x;
};
But when i tested it with input -2147483648, the function return wrong answer but it is good for Python for exemple.
It is because of some problems with Javascript to deal with signed integer?
Thanks for your response.
Edit:
Oups, i ignore the fact that power of two couldn't be negative.

We can just use n > 0 and simultaneously couple our two statements here.
This'll get accepted in JavaScript:
const isPowerOfTwo = function(n) {
return n > 0 && (n & (n - 1)) === 0;
};
console.log(isPowerOfTwo(-2147483648))
Python doesn't have that integer overflow.
class Solution:
def isPowerOfTwo(self, n):
if n < 1:
return False
while not n & 1:
n >>= 1
return n == 1
We can also simply return false if n < 1 first. Here are implementations of the same idea in Java/C++:
Java
public final class Solution {
public static final boolean isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
while ((n & 1) == 0) {
n >>= 1;
}
return n == 1;
}
}
C++
static const struct Solution {
static const bool isPowerOfTwo(int n) {
if (n < 1) {
return false;
}
while (!(n & 1)) {
n >>= 1;
}
return n == 1;
}
};
References
For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis1, 2.

Yes for all negative integer the result is wrong because of the sign.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63.
For more information look https://www.w3schools.com/js/js_numbers.asp

Related

Trying to understand recursion in JS... check my simple code

I am trying to wrap my head around recursive functions. I've tried a number of entry level exercises with no success. For example, I put this code into JS fiddle. I intended for it to take the sum of all numbers from 1 to n.
function sumAll(n) {
if (n == 1 ) {
return 1;
} else if (n > 1) {
return sumAll(n--) + n;
}
}
console.log(sumAll(3));
feeding 3 to the function should give me '6'. I get an error, though.
The -- suffix operator will evaluate to the original value of n, and the subtraction from n will happen afterwards (which is also not desired as you still want to do + n). That means the recursive call gets the same value for n as the caller, and so you don't get closer to the end...
Don't use -- here, but -1:
function sumAll(n) {
if (n == 1 ) {
return 1;
}
else if (n > 1) {
return sumAll(n-1) + n;
}
}
console.log(sumAll(3));
Perhaps you will enjoy a repeatable technique that can guide you through designing your recursive function. Let's solve sumAll using inductive reasoning -
If n is zero, return the empty sum, zero
(inductive) n is negative or positive. If n is negative, return the negative result of the subproblem sumAll(-n)
(inductive) n is positive. Return n plus the result of the subproblem sumAll(n - 1)
function sumAll(n) {
if (n == 0) // 1
return 0
else if (n < 0) // 2
return -sumAll(-n)
else
return n + sumAll(n - 1) // 3
}
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55
Here is sumAll written using a switch instead. It behaves identically but maybe you will find the syntax nicer to read -
function sumAll(n) {
switch (true) {
case n == 0: return 0 // 1
case n < 0: return -1 * sumAll(-n) // 2
default: return n + sumAll(n - 1) // 3
}
}
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55
Here is sumAll again as a pure, functional expression -
const sumAll = (n = 0) =>
n == 0 // 1
? 0
: n < 0 // 2
? -1 * sumAll(-n)
: n + sumAll(n - 1) // 3
console.log(sumAll(-10), sumAll(0), sumAll(10))
// -55 0 55

Recursion counter doesn't work in codewars kata

Currently trying to complete the persistent bugger kata in code wars.
I need to return the number of times the input has to be multiplied until it is reduced to a single number (full task instructions below).
Everything appears to work apart from the count. when I console log, the number of times it logs and runs is correct, but instead of incrementing such as 1,2,3 it will be something like 2,2,4.
So instead of returning 3, it returns 4.
I try to not ask for help with katas, but this time I am completely at a loss as to why the count is firstly skipping numbers and also not incrementing.
Task:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
My function:
function persistence(num) {
//console.log('here', num)
if(num < 10) return 0;
if(num === 25) return 2
let spl = num.toString().split('');
let result = 1;
let count = 1;
spl.forEach((s) => {
let int = parseInt(s)
result *= int;
//count++;
})
//console.log(result)
if(result > 9) {
persistence(result)
count++;
}
// console.log('count-->', count)
return count;
}
A sub issue is that the input 25 always returns a count 1 less than it should. My fix is poor I know, again any advice would be much appreciated.
Spoiler alert: this contains a solution. If you don't want that, stop before the end.
You don't really want to work with count, since as people point out, it's a local variable. You also don't work too hard to special case the result if it's a single digit. Let the recursion handle it.
Thus:
function persistence(num) {
//console.log('here', num)
if(num < 10) return 0;
//still here, must be 2 or more digits
let spl = num.toString().split('');
let result = 1;
spl.forEach((s) => {
let int = parseInt(s)
result *= int;
})
//console.log(result)
return 1 + persistence(result)
}
As you already have a complete solution posted here with fixes to your implementation, I will offer what I think is a simpler version. If we had a function to create the digit product for us, then persistence could be this simple recursion:
const persistence = (n) =>
n < 10 ? 0 : 1 + persistence (digProduct (n))
You already have code for the digit product, and while it's fine, a mathematical approach, rather than a string-base one, is somewhat cleaner. We could write it -- also recursively -- like
const digProduct = (n) =>
n < 10 ? n : (n % 10) * digProduct (Math .floor (n / 10))
or instead we might choose (n / 10) | 0 in place of the floor call. Either is reasonable.
Putting it together, we have:
const digProduct = (n) =>
n < 10 ? n : (n % 10) * digProduct ((n / 10) | 0)
const persistence = (n) =>
n < 10 ? 0 : 1 + persistence (digProduct (n))
const tests = [39, 999, 4, 25]
tests.forEach (n => console.log (`${n} --> ${persistence(n)}`))

Is finding the factorial of 5000 possible in javascript

I want to find the factorial of 5000 but once I try to pass 100 it'll return infinity. Is there are way to bypass this and get the result? I am trying to get the time it takes to solve this.
function testSpeed(n) {
if (n > 0 && n <= 1) {
return 1;
} else {
return n * testSpeed(n-1);
}
}
console.log(testSpeed(5000));
As you've noticed, Javascript numbers can only get so big before they just become "Infinity". If you want to support bigger numbers, you'll have to use BigInt.
Examples:
// Without BigInt
console.log(100 ** 1000) // Infinity
// With BigInt
// (stackOverflow doesn't seem to print the result,
// unless I turn it into a string first)
console.log(String(100n ** 1000n)) // A really big number
So, for your specific bit of code, all you need to do is turn your numeric literals into BigInt literals, like this:
function testSpeed(n) {
if (n > 0n && n <= 1n) {
return 1n;
} else {
return n * testSpeed(n-1n);
}
}
console.log(String(testSpeed(5000n)));
You'll find that youe computer can run that piece of code in a snap.
This seems to give the correct result (according to https://coolconversion.com/math/factorial/What-is-the-factorial-of_5000_%3F)
const longFactorial = (num) => {
let result = num;
for (let i = 1n; i < num; i++) {
result = result * (num - i)
}
return String(result);
}
console.log(longFactorial(5000n));
I can receive for 170! maximum:
function factorial (y){
if (y ==0 || y ==1){
return 1;
}
else {
f = y - 1;
while (f >= 1) {
y = y * f;
f--;
}
return y;
}
}
console.log(factorial(170));

Confusion about the behavior between arithmetic operators and functions?

function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) ); // 8
source = https://javascript.info/recursion
Hello all! I'm confused about the second return statement of this function:
return x * pow(x, n - 1);
I'm just looking for either some clarification or a reference to that behavior.
From my perspective, it looks like x is multiplied only by the first parameter of the function, and the n-1 is ignored.
(How does n-1 affect the result <- original question)
Sorry, I messed up the original question...
I want to ask how does javascript interprets that multiplication. When multiplying an integer and a function, I don't quite understand what's happening. How does javascript choose what to multiply with more than one parameter?
pow(2, 3) = 2 * pow(2, 2) = 2 * 2 * pow(2, 1) = 2 * 2 * 2
You are not actually calculating a product with n - 1, but refer to n as a counter. This is equivalent to
var result = 1;
while (n >= 0) {
result *= x;
n--;
}

Function to determine largest prime factor

I am trying to write a function in JS that returns a number's maximum "prime" factor. For example, if I ran maxPrimeFactor(57), I should return a 19. However, my function only works part of the time. I have written a helper function called isPrime that returns a boolean that indicates whether a given number is prime.
Can anyone spot-check my logic and give me pointers as to where I may be going wrong/how I can improve my algorithm and implementation? Any help is appreciated.
function isPrime(n){
var flag = true;
for (var i = 2; i < n / 2; i++) {
if (n % i == 0) {
flag = false;
return flag;
}
}
return flag;
}
function maxPrimeFactor (n) {
var max = 1;
for (var i = 1; i <= n/2; i++) {
if (n % i == 0 && isPrime(i)) {
max = i;
}
}
return max;
}
1 is not prime, so if you pass 1 to the function it will return 1 as the max prime factor which is incorrect. Perhaps a check returning a value like NaN or undefined may be helpful to prevent invalid values, this depends on if you need to limit the scope of the inputs.
if (n < 2) {
return NaN;
}
You also need to consider the case for when n is prime. A possible way around this more efficiently would be to initialize max to n, and then if max is never set again, the max prime is n.
function maxPrimeFactor (n) {
var max = n;
for (var i = 2; i <= n/2; i++) {
if (n % i == 0 && isPrime(i)) {
max = i;
}
}
return max;
}
Since the algorithm only cares about the greatest prime factor, if you start counting down from n/2, you can further optimize the function to return the first prime factor that is found, otherwise return the number.
As the local var flag in isPrime() isn't making the code more readable or functional I would remove it . (Also, no need to loop to n/2 as no number has a prime greater than it's square root);
function isPrime(n){
for (var i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I give U a code written in C++ below:
#include <cstdio>
#include <cmath>
int max(int x, int y)
{
return x > y ? x : y;
}
int maxPrime(int x)
{
int mx = -1;
int curX = x;
/*i * i <= x is correct, because there is only one prime factor larger than
Sqrt(x), it's power must be 1, and actually it is curX after this loop, because
all prime factor less or equal than Sqrt(x) is eliminated.*/
for(int i = 2; i * i <= x; ++i)
{
while(curX % i == 0)
{
/*Here i must be a prime. consider Prime factorization
x = p1^q1 * p2^q2 * p3^q3...(p1<p2<p3...)
the first number that satisfied x % i == 0 must be p1, it's prime!
and p2 > p1 so I can continue to enumerate i, don't need to reset i to 2.
curX = x/(p1^q1 * p2^q2 * ... * pj^qj) and i = p[j+1]
*/
curX /= i, mx = max(i, mx);
}
}
return max(mx, curX);
}
int main()
{
int n;
scanf("%d", &n);
//I suppose n is positive
if(n == 1) //1 is not prime
printf("No solution\n");
else
printf("%d\n", maxPrime(n));
return 0;
}
This code reaches a worst case running time O(Sqrt(n))
And your code is wrong, because when n is a prime, your code cannot get the right answer.
And your code's efficiency is not good.
If you want a faster code, you can learn Pollard Rho or SQUFOF.

Categories

Resources