Getting Boolean values if a number is a prime number in JavaScript - javascript

I am trying to solve this problem where I need to print true or false on the console depending on the number (true if a number is Prime and false if it is not). I seem to have the solution but I know there is a mistake somewhere because I get different answers if I change the boolean values of the 2 isPrime variables.
Here is the question:
Return true if num is prime, otherwise return false.
Hint: a prime number is only evenly divisible by itself and 1
Hint 2: you can solve this using a for loop.
Note: 0 and 1 are NOT considered prime numbers
Input Example:
1
7
11
15
20
Output Example:
false
true
true
false
false
My code:
function isPrime(num){
let isPrime = '';
for(let i = 2; i <= Math.sqrt(num); i++){
if(num % i === 0){
isPrime = false;
} else {
isPrime = true;
}
}
return isPrime;
}
isPrime(11);

You are very close. I will build on top of your solution. You need to return false as soon as you detect that the number is not prime. This avoids us making additional redundant calculations.
You also did not take into account the first hint.
Hint - Note: 0 and 1 are NOT considered prime numbers
For this you can simply return false if number is 0 or 1.
function isPrime(num) {
if (num === 0 || num === 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
Also in your code you are using a variable isPrime to keep track of boolean values while initialising it with an empty string. This is not correct. Javascript allows this because it's weakly typed, but this is misleading. So in future if you define a variable for boolean value don't initialise it with a string ;)
To address your comment further. If you do want to stick with having a flag in your code, then you can initialise isPrime with true instead of an empty string.
That way you can get rid of the else part in the for loop, making the code shorter. I used code provided by #Commercial Suicide (by the way he did say that there are more elegant solutions) as an example:
function isPrime(num) {
let flag = true;
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (flag) {
if(num % i === 0) {
isPrime = false;
flag = false;
}
}
}
return isPrime;
}
const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];
numbers.forEach((item, i) => {
if (isPrime(item) === booleans[i]) {
console.log("CORRECT");
} else {
console.log("WRONG");
}
})
You can then go a step further and remove the flag variable.
function isPrime(num) {
let isPrime = true;
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (isPrime) {
if(num % i === 0) {
isPrime = false;
} else {
isPrime = true;
}
}
}
return isPrime;
}
But now it should become even more clear that those flags are actually redundant, as I pointed out initially. Simply return false as soon as you detect that the number is not prime to avoid further unnecessary loop runs. From my experience in javascript over the years I can see that we are heading towards functional programming mindset. It helps to avoid variable mutations generally.

It's because your isPrime variable can be overriding many times, simple flag (for example) will prevent this issue. I have also added check for 0, 1 and 2. There are more elegant ways to do that, but I wanted to keep your logic, here is an example with some tests:
function isPrime(num) {
let flag = true;
let isPrime = '';
if (num === 0 || num === 1) return false;
if (num === 2) return true;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (flag) {
if(num % i === 0) {
isPrime = false;
flag = false;
} else {
isPrime = true;
}
}
}
return isPrime;
}
const numbers = [1, 7, 11, 15, 20];
const booleans = [false, true, true, false, false];
numbers.forEach((item, i) => {
if (isPrime(item) === booleans[i]) {
console.log("CORRECT");
} else {
console.log("WRONG");
}
})

Related

isPrime function logs 15 as true (15 is not a prime number)

function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){ return false
} else if (num === 2) {
return true
}
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false
} else {
return true
}
}
}
Tried changing the conditional of the for loop but still comes out as true.
Wait until the whole loop finishes before returning true, otherwise you only check the first iteration and make a decision right away whether the input is prime before checking all the rest of the numbers. Also surely you don't need to iterate the entire length of the number, Math.ceil(num/2) + 1 should suffice. This is because there's no point to ever check if anything larger than half of a number will factor into that number. (This will make a big impact on larger numbers)
function checkPrime(){
var num = document.getElementById("num").value;
var result = document.getElementById("result");
var arr=[];
if (num.length===0)
result.innerHTML = "Please, specify a number.";
else if (num<0)
result.innerHTML = "Please, specify a positive number.";
else
result.innerHTML = isPrime(num).toString();
return false;
}
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2)
return false;
else if (num === 2)
return true;
const max = Math.ceil(num/2) + 1;
for (let i = 2; i < max; i++) {
if (num % i === 0)
return false;
}
return true;
}
<form onsubmit=" return checkPrime()">
<label>Enter a number check prime</label>
<input type="number" id="num" name="num"><br>
<input type="submit" value="Submit" id="submit">
<div id="result"></div>
</form>
This means you are testing any number entered to return a bool (true/false) if it is a prime number.
I would modify your code a little bit to give this function a correct answer.
function isPrime(num){
// loop numbers to see if any num is divisble by that number
if (num < 2){
return false
}else if(num==2){
return true;
}else{
for (let i = 2; i < num; i++) {
if (num % i == 0) {
return false;
//break;
}
}
return true;
}
}

JavaScript Loops With If and Else

how come the following is not accurately logging whether a number is prime or not?
function isPrime2(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return console.log(false); break;
} else{return console.log(true)}
}
}
isPrime2(33)returns true, even though it is a prime number.
If i = 2, then the console will log true since 33/2 = 16.5
But since the loop isn't over, the next i value is i=3,
so shouldn't the console log false and then break out of the loop completely, leaving the final answer to be false?
There are two problems here.
Your logic is broken
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
} else {
return console.log(true)
}
}
}
isPrime2(33);
i starts at 2.
if(num % i === 0) is false, so we go to else
else{return console.log(true)} causes it to log true and exit the function.
Your failure condition is triggered when the first test fails instead of waiting for the loop to finish with a success condition for any of the tests.
33 is not a prime
It is divisible by 3 and 11.
function isPrime2(num) {
for (let i = 2; i < num; i++) {
const remainder = num % i;
console.log({
remainder
});
if (remainder === 0) {
return console.log(false);
break;
}
}
return console.log(true)
}
isPrime2(33);

Why does function return undefined when it explicitly is told to return true?

I was trying to solve the following coding exercise.
We have two special characters. The first character can be represented
by one bit 0. The second character can be represented by two bits (10
or 11).
Now given a string represented by several bits. Return whether the
last character must be a one-bit character or not. The given string
will always end with a zero.
example:
Input: bits = [1, 0, 0] Output: True
Below is my solution for the above challenge. Why is this returning undefined? If I use [1,0,1,0] as input, it should return true but I am getting undefined. I am explicitly writing true in the return statement and not the results of a variable.
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
isOneBitCharacter(bits.slice(1));
} else {
isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);
I guess you are missing returns. Here is adjusted code:
var isOneBitCharacter = function(bits) {
console.log(bits);
var length = bits.length;
if (length == 1) {
return true;
}
if (length == 0) {return false;}
// added return here and next statements
if (length == 2 && bits[0] === 1) {
return false;
}
if (bits[0] === 1) {
return isOneBitCharacter(bits.slice(1));
} else {
return isOneBitCharacter(bits.slice(2));
}
};
isOneBitCharacter([1,0,1,0]);

Printing 100 to 200, with three exceptions?

I am trying to write a program that prints the numbers from 100 to 200, with three exceptions:
If the number is a multiple of 3, the string "yes" should be returned instead of the number.
If the number is a multiple of 4, the string "yes and yes" instead of the number should be returned.
If the number is a multiple of both 3 and 4, the string "yes, yes and yes" instead of the number.
I am new to JavaScript so I try to do this step by step.
I wrote this code to print the numbers from 100 to 200:
function hundredTwoHundred() {
result = [];
for (let i = 100; i <= 200; i++) {
result.push(i);
}
return result;
}
console.log(hundredTwoHundred());
Then I tried to use else/if for the exceptions:
function hundredTwoHundred() {
result = [];
for (let i = 100; i <= 200; i++) {
if (i % 3 == 0) {
console.log("yes");
} else if (i % 4 == 0) {
console.log("yes and yes")
} else if (i % 3 == 0 && i % 4 == 0) {
console.log("yes, yes and yes");
} else {
result.push(i)
}
}
return result;
}
console.log(hundredTwoHundred());
The code of course, does not work. I have tried moving result.push(i) around, but I don't want to just mindlessly move things around, without knowing the reasoning behind it.
How do I use conditional operators to find these exceptions? What am I doing wrong?
Thank you.
You need to test if the number is (divisible by 3 and divisible by 4) before checking whether it's (individually) divisible by 3 or 4, otherwise the first condition if (i % 3 == 0) will evaluate to true and you'll get yes rather than yes, yes and yes. You should also push to the result in the conditionals rather than console.logging in the conditionals, since you want to create an array of numbers and yeses and then console.log the whole constructed array afterwards.
Also make sure to declare the result with const (or var, for ES5) - it's not good to implicitly create global variables.
Also, although it doesn't matter in this case, when comparing, it's good to rely on === by default rather than == - best to only use == when you deliberately want to rely on implicit type coercion, which can result in confusing behavior.
function hundredTwoHundred() {
const result = [];
for (let i = 100; i <= 200; i++) {
if (i % 3 === 0 && i % 4 === 0) {
result.push("yes, yes and yes");
} else if (i % 3 === 0) {
result.push("yes");
} else if (i % 4 === 0) {
result.push("yes and yes")
} else {
result.push(i)
}
}
return result;
}
console.log(hundredTwoHundred());
If a number is a multiple of 3 and 4, then it is a multiple of 12. I’d also use a switch statement, so you can rewrite as follow:
for (let i = 100; i <= 200; i = i + 1) {
switch (0) {
case i % 12: console.log('yes, yes and yes'); break;
case i % 4: console.log('yes and yes'); break;
case i % 3: console.log('yes'); break;
default: console.log(i);
}
}
If you want it as an array:
// Fill an array with numbers from 100 to 200
const arr = Array(101).fill().map((_, i) => i + 100);
// Map it to numbers and strings
const hundredTwoHundred = arr.map(i => {
switch (0) {
case i % 12: return 'yes, yes and yes';
case i % 4: return 'yes and yes';
case i % 3: return 'yes';
default: return i
}
});
// Print it:
console.log(hundredTwoHundred);
When you have a complex set of conditions you need to be careful with the order in which you evaluate them.
function logExceptions(start, end) {
var divisibleByThree, divisibleByFour;
for (var i = start; i <= end; ++i) {
divisibleByThree = i % 3 == 0;
divisibleByFour = i % 4 == 0;
if (divisibleByThree && divisibleByFour) {
console.log("yes, yes and yes");
}
else if (divisibleByThree) {
console.log("yes");
}
else if (divisibleByFour) {
console.log("yes and yes");
}
else {
console.log(i);
}
}
}
logExceptions(100, 200);
If you want to save the result in an array and only later print it:
function logExceptions(start, end) {
var result = [];
var divisibleByThree, divisibleByFour;
for (var i = start; i <= end; ++i) {
divisibleByThree = i % 3 == 0;
divisibleByFour = i % 4 == 0;
if (divisibleByThree && divisibleByFour) {
result.push("yes, yes and yes");
}
else if (divisibleByThree) {
result.push("yes");
}
else if (divisibleByFour) {
result.push("yes and yes");
}
else {
result.push(i);
}
}
return result;
}
console.log(logExceptions(100, 200).toString());

Prime factor in javascript, why is this case not working?

I'm writing a primality checker in in j/s and I was wondering why I'm getting true as a return for when I test 55... It seems to work fine for all the other cases I checked just not 55, can someone tell me where I went wrong?
var isPrime = function(num){
if (num === 2){
return true;
}
else if(num%2 === 0){
return false;
}
else{
var i = 2;
while(i<num){
if((num/i) % i === 0 ){
return false;
}
i++
}
return true;
}
};
Thanks in advance and apologies for the noobness!
if((num/i) % i === 0 ){
return false;
}
What is this case?
Shouldn't it be
if(num % i === 0 ){
return false;
}
Just as #Andrey pointed out, your if statement inside the while loop is not correct. For 55 at i=5 you should get false for 55 being prime, but 55/5 % 5 == 1 Also you could use just == instead of === for logical equals, since === checks if both values and type are equal, which is not necessary here.
Try this.
var isPrime = function isPrime(value) {
var i = 2;
for(i; i < value; i++) {
if(value % i === 0) {
return false;
}
}
return value > 1;
};
Even if your bug may be solved, I'd recommend to think about some other aspects to optimize your code:
Clarify your corner cases: In the beginning, check for n<2 -> return false. At least to math theory primes are defined as natural number larger then 1, so 1 is by definition not a prime like all the negative numbers. Your code won't handle negative numbers correctly.
You don't have to check all divisors up to n-1. You can obviously stop checking at n/2, but there are even proofs for tighter bounds which means you can stop checking already at √n if I'm right. To further optimize, you don't have to check even divisors >2.
else {
var i = 3;
while ( i < num/2 ) {
if( num % i == 0 ) {
return false;
}
i+=2;
}
return true;
}
See https://en.wikipedia.org/wiki/Primality_test for details about testing of primes.
P.S: I just wrote the code here in the text box, but it looks like it might work.

Categories