This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
I have written the below code to check if a number is prime, and it works correctly. But to my amazement when it pass 25 as a value, it returns "true" instead of "false" because 25 is not a prime number.
So I decided to share. Please, what I am doing wrong here?
function isPrime(number) {
return number % 2 !== 0 && number % 3 !== 0 ? true : false;
}
isPrime(4) returns false;
isPrime(23) returns true;
isPrime(25) returns true;
"(Here is where I got alarmed. 25 Should return false too)
Your condition is very minimal. What if the number is not divisible by 2 or 3 but divisible by 5 or 7? Besides how come isPrime(23) returns false is okay? 23 is a prime as well it should return true. What you need to do is iterate through all the number from n-1 to 2(here n is the number you are checking) and check if any of the number divides n without a remainder. You can do the following,
function isPrime(number) {
let isPrimeNum = true;
for(let i = number-1; i>=2; i--) {
if(number%i === 0) isPrimeNum = false;
}
return isPrimeNum;
}
console.log(isPrime(23));
console.log(isPrime(25));
There is a lot of way you can optimize the above solution. I kept it as a challenge for you to find out and do by yourself. You can start from here.
Your code only checks if the input is divisible by 2 or 3. However, a prime number (by definition) is a number that's only divisible by 1 and itself.
Therefore, you have to check every number less than or equal to sqrt(n). (It's enough to scan this area, as if there's a divisor greater than that, it must have a pair that falls in that range.
The loop iterates upwards, so it can early-return, if the number is divisible by a small prime.
function isPrime(number){
if(number <= 1 || number !== Math.floor(number))
return false
const sqrtNumber = Math.sqrt(number)
for(let n = 2; n <= sqrtNumber; n++)
if(!(number % n))
return false
return true
}
console.log(isPrime(-42)) //false
console.log(isPrime(1)) //false
console.log(isPrime(3.14)) //false
console.log(isPrime(4)) //false
console.log(isPrime(23)) //true
console.log(isPrime(25)) //false
Related
//This program calculates how many times a number is divisible by 2.
//This is the number and the amount of times its been split into 2.
let Num=64
let divisible=0
//This is the ternary operator, it basically asks a question.
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
Num/=2;
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
num/=2
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
//Once the statement evaluates to false it writes the amount of times the number has been divided
by 2 into the document.
You could try it with a loop.
let num=64;
let divisible=0;
while(num % 2 === 0) {
num /= 2;
divisible++;
}
console.log(divisible);
document.write(divisible);
There are several issues with this code. Some of the comments have pointed out the looping concerns. However, one that stands out that won't be addressed with a loop is your misuse of the post-fix increment operator, ++. This operator returns the value and then increments the value, so divisible = divisible++ will result in divisible remaining unchanged. Based on your intent, all you need to do is divisible++.
Try the following:
while(true){
if(Num % 2 === 0){
divisible++;
Num /=2;
}
else{
document.write(divisible);
break;
}
}
Here as per example given for 64 and no looping is provided , it will never go to
document.write(divisible) statement in 3 step provided above . That's why nothing getting printed .
Moreover , divisible=divisible++ doesn't make any sense . Here , since it is postfix operartor , first value will be assigned then it will be incremented so value of divisible will be 0 only .
Num % 2 === 0 ?divisible++ : document.write(divisible);
And , as per my understanding document.write accepts string parameter but here divisible is of number type .
This question already has answers here:
Math.pow with negative numbers and non-integer powers
(2 answers)
Closed 3 years ago.
I am trying to write a code about changing numbers to its cube root but whenever i enter a negative number, i receive NaN error.
Tried to use string to number function called Number
let number = prompt("Enter a number");
if (number > 0 || number < 0){
let x = number**(1/3);
alert(x);
}
else if (number == 0){
alert(number);
}
else{
alert("Error");
}
I enter -8 for example, i expect it will give me -2 as result but i receive NaN
This is because cube-root of a negative number has complex numbers as solutions along with a negative real number, to get the negative real number you have to write a simple logic:
function cubeRoot(number){
const isNegative = number < 0;
const cubeRoot = Math.pow(Math.abs(number), 1/3);
return isNegative ? -cubeRoot : cubeRoot;
}
console.log(cubeRoot(-8));
console.log(cubeRoot(0));
console.log(cubeRoot(8));
There is a library available to do this: math.js
console.log(math.cbrt(-8));
console.log(math.cbrt(0));
console.log(math.cbrt(8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/6.2.1/math.js"></script>
I am trying to understand this code from Eloquent JavaScript:
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
unless(n % 2, function() {
console.log(n, "is even");
});
});
// → 0 is even
// → 2 is even
I get that it says, run the following code 3 times testing with 0,1,2:
if (!n%2) function(n) {
console.log(n, "is even");
});
What I don't get is how we get true/false from (!n%2)?
Is (!n%2) the same as (!n%2 == 0)?
Logical NOT ! has higher precedence than modulo operator %.
Thus, (!n%2) is equivalent to (!n) % 2 which will always return 0 a falsy value except when n = 0.
Whereas (!n%2 == 0) will return true(again except 0).
They both are not equal, in fact they are opposite of each other(falsy vs truthy value).
You need !(n % 2).
Or simply to check if number is even
n % 2 === 0
Your test code you wrote is not equivalent to the sample code from the article.
In the sample code, n % 2 is evaluated first, and the result is passed into the unless function. There, you are performing a Logical Not operation against the result.
If n is even, n % 2 will pass 0 to unless. A Boolean comparison of 0 returns false, and the ! negates the result (logical not), so !0 == true. this, in turn, causes the then function to fire.
If n is odd, the opposite occurs. Some value other than 0 is passed, which evaluates to false, causing then to not fire.
In contrast, your attempt to reproduce the sample code without using Higher-Order functions won't work the same way. !n % 2 will perform the Logical Not on n first, then try to modulo the result. !(n % 2) is a better representation of the sample code.
!Boolean(n%2) should work as a way to determine whether one is even or odd.
Remember that Boolean does not follow BIDMAS.
It does !n first where n is treated as a Boolean so that the numerical value of 0 is treated as false and any other numerical value is treated as true. The exclamation mark inverts the logic state of n.
Now the %2 converts the Boolean back to an integer where true is 1 and 0 is false. !n = 0 returns 0 and !n = 1 returns 1.
Using !n%2 in an if statement converts it back to a Boolean (1 = true, 0 = false).
Thus if n = 0 then the if statements proceeds because it returned true. If n != 0 (!= meaning not equal) then if statement is skipped because it returned false.
No, it's not. As stated here the "!" operator has highest precedence than "%" so the expression will return true if n is 0 and false if n is different from 0.
More in detail, suppose n is 2. the execution of the expression is:
(!n)%2
(!2)%2
0%2
0
so it is false, now for n=0
(!0)%2
1%2
1
so it is true. It is the opposite behavior of (!n%2 == 0) that returns true if n is different from 0 and false otherwise since == has less precendence and the comparison with 0 is executed at the end of the calculation above. You can easily convince yourself by using this simple javascript with different values of n:
n = 1;
if(!n%2)
{
document.getElementById("par1").innerHTML="true";
}
if(!n%2 == 0)
{
document.getElementById("par2").innerHTML="true";
}
I understand that "a" solution is:
function Factorial(number)
{
if(number == 0 || number == 1){
return 1;
}
return number * Factorial(number -1);
}
I want to understand what exactly is going on. I understand what is going on all the way to the last part when number == 1.
If we were to take a simple example of say 3!
3 is not equal to 0 or 1 so we return 3 * Factorial(2)
2 is not equal to 0 or 1 so we return 2 * Factorial(1)
1 is equal to 1 so we return 1
How do we know when to stop? Is it the fact that we return 1 that tells the function to stop?
If that is the case, why does the function not stop when we first return 3 * Factorial(2)? Is it because it's returning a function so that it must continue until it no longer returns a function?
Thank you
I think you have to understand the logic of factorial.
So factorial is just products, indicated by an exclamation mark ie, if you write
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1
Hope you find the pattern, so you can write the above factorials as:
0! = 1
1! = 1
2! = 2*1!
3! = 3*2!
4! = 4*3!
5! = 5*4!
So in your function you are using the similar logic.
Now in your function
if(number == 0 || number == 1)
{
return 1;
}
The above logic is to cover the first two cases i.e, 0! and 1! And
return number * Factorial(number -1);
is for the rest of the numbers.
So you are using the recursive technique of solving the factorial problem.
To understand recursion, lets take a number say 5 i.e., we want find the value of 5!.
Then first your function will check
if(number == 0 || number == 1)
which is not satisfied, then it moves to the next line ie,
return number * Factorial(number -1);
which gives
5*Factorial(5-1) which is equal to 5*Factorial(4)
Now on subsequent calls to your Factorial function it will return the value like below:
5*(4*Factorial(4-1)) which is equal to 5*(4*Factorial(3))
5*(4*(3*Factorial(3-1)) which is equal to 5*(4*(3*Factorial(2)))
5*(4*(3*(2*Factorial(2-1)))) which is equal to 5*(4*(3*(2*Factorial(1))))
Now when it returns factorial(1) then your condition
if(number == 0 || number == 1)
is satisfied and hence you get the result as:
5*4*3*2*1 = 120
On a side note:
Beware that factrial is used only for positive integers.
Recursion relies on what is called a base case:
if(number == 0 || number == 1){
return 1;
}
That if statement is called your base case. The base case defines when the recursion should stop. Note how you are returning 1 not returning the result of a call to the function again such as Factorial(number -1)
If the conditions for your base case are not met (i.e. if number is NOT 1 or 0) then you proceed to call the function again with number * Factorial(number - 1)
If that is the case, why does the function not stop when we first return 3 * Factorial(2)?
Your simple example of 3! can be elaborated like this :
return 3 * Factorial(2)
will then be replaced by
return 3 * (2 * Factorial(1))
which then will be replaced by
return 3 * (2 * 1) // = 6 Hence 6 is returned at last and recursion ends.
How do we know when to stop?
When all your Factorial(value) is replaced by a returned value we stop.
Is it the fact that we return 1 that tells the function to stop?
In a way, yes. Because it is the last returned value.
It is called recursion.
This function is called like this
var result = Factorial(3);
in Factorial function
First time
return 3*Factorial(2);
Now here return statement doesnt get executed insted Factorial is called again..
so second time
return 2*Factorial(1);
again in Factorial(1)
Third time
return 1;
So go to second
return 2*1;
Next to first
return 3*(2*1);
Finally
var result = 3*2*1 = 6.
The function is recursing (calling itself) - and taking one from "number" each time.
Eventually (as long as its a positive integer you call it with, otherwise you'll probably get an infinite loop) you'll always hit the condition (number == 1) so instead of recursing further, it'll return 1 rather than call the function again.
Then, once you have hit the bottom (1), it'll start to run the function and work back up the other way along the function call stack, using the previous result each time:
1 = 1
(2*1) = 2
(3*2) = 6
(4*6) = 24
etc
So the final return statement from the function will return the required result
I can't figure out how this recursive call works. Using the not operator in the recursive call somehow makes this function determine if the argument given is odd or even. When the '!' is left out fn(2) and fn(5) both return true.
This example is taken out of JavaScript Allonge free e-book, which, so far has been excellent.
var fn = function even(n) {
if (n === 0) {
return true;
}
else return !even(n - 1);
}
fn(2); //=> true
fn(5); //=> false
If n === 0 the result is true.
If n > 0 it returns the inverse of n - 1.
If n === 1 it will return !even(0), or false.
If n === 2 it will return !even(1), or !!even(0), or true.
If n === 3 it will return !even(2), or !!even(1), or !!!even(0), or false.
And so on...
In general:
If n is even, the result is inverted an even number number of times, meaning it will return true.
If n is odd, the result is inverted an odd number number of times, meaning it will return false.
The above function reurns recursively the negation of it self.The base-case is when the number provided becomes zero and each time the function calls it self the number is decreased by one. As a result we have n recursive negations starting with true at base-case (where n is the number provided). For an odd number of negations given true as a starting value you get false as the result and for an even number you get true.
In summary:
Starting from given n
recursive reduction of n
Basecase: n=0 returns true
recursive negation of returned value(starting from true at base-case)
Result:
for odd number of negations the value returned is false
for even number of negations the value returned is true
Lets say we have example n=5
recursive reduction of n. Values of n at each level:
5
4
3
2
1
0 (base-case)
returned values at each level:
true (base case)
!true
!!true
!!!true
!!!!true
!!!!!true
A variant of you code could be:
function even(n) {
if (n === 0)
return true;
else
return odd(n - 1);
}
function odd(n) {
if (n === 1)
return true;
else
return even(n - 1);
}
We know that all positive numbers starting from 0 alternating between being even and odd. What you example does is defining odd to be !even which is correct since odd/even are disjoint. In your version using !, the not needs to be done as a continuation. That means every instance need to do something with the answer after the recursive call returns.