Hello I am trying to refactor my function but it doesn't seem to be working properly. It works fine normally which is the commented code. Am I writing this wrong or is there a fundamental flaw in my code?
function isPrime(num) {
// if (num <= 1){
// return false
// } else {
// for(var i = 2; i < num; i ){
// if(num % i === 0) return false;
// }
// }
num <= 1 ? false : {
for(let i = 2; i < num; i ){
num % 1 === 0 ? false
}}
return true;
}
Thanks
CodePudding user response:
As far as I can tell, no language having the ternary operator allows running a block of statements, which is what you are doing. The ternary operator is a shorthand version of:
let result;
if (<condition>)
result = resultTrue;
else
result = resultFalse;
Unless JavaScript stabs be in the back on this one, for
is a statement that doesn't return anything, and therefore cannot be used the way you want.
The best you could do, I guess, would be:
function isPrime(num) {
if (num <= 1) {
return false;
}
for(var i = 2; i < num; i ) {
if(num % i === 0) return false;
}
}
The else
part omitted since hitting the line after the if
necessarily means that the condition for it was not met.
CodePudding user response:
Technically what you have can be brought to life with an IIFE:
function isPrime(num) {
return num <= 1 ? false :
(n => {
for (let i = 2; i < n; i ) {
if (n % i === 0) return false;
}
return true;
})(num)
}
for (let i = 0; i < 10; i ) {
console.log(i, isPrime(i));
}
Now it works and there is a ternary operator inside.
Even the attempt without return
can be done, just you need isPrime
made into an arrow function:
let isPrime = num => num <= 1 ? false :
(n => {
for (let i = 2; i < n; i ) {
if (n % i === 0) return false;
}
return true;
})(num);
for (let i = 0; i < 10; i ) {
console.log(i, isPrime(i));
}
Tadaam, the num <= 1 ? false :
part is literally there in the first line, without that nasty return
.
But realistically this is not how isPrime
should be implemented, your very first attempt is the best one so far.
If you want an actual improvement, use the fact that divisors come in pairs. If x
is a divisor of num
, then num/x
is also divisor of num
. So if you were looking for all divisors of num
, you would find them in pairs as soon as x=num/x=sqrt(num)
, so it's enough to check numbers between 2
and Math.floor(Math.sqrt(num))
, inclusive. As you preferably don't want JS to calculate this number in every iteration (when checking the condition), you could count downwards, so
for (let i = Math.floor(Math.sqrt(num)); i >= 2; i--)