I'm trying to complete the Codewars challenge that asks you to check if a number is a prime number. For whatever reason, my solution doesn't seem to work for the square of odd prime numbers (e.g. 9
returns true
instead of false
).
function isPrime(num) { if (num === 2) { return true; } else if (num > 1) { for (var i = 2; i < num; i++) { if (num % i !== 0) { return true; } else if (num === i * i) { return false } else { return false; } } } else { return false; } } console.log(isPrime(121));
P.s. I included that second else/if statement because I was trying to solve the problem.
To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can't be a prime number. If you don't get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number (see table below).
Per Wikipedia, a prime number ( or a prime ) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Time complexity: O(sqrt(n))
Space complexity: O(1)
const isPrime = num => { for(let i = 2, s = Math.sqrt(num); i <= s; i++) if(num % i === 0) return false; return num > 1; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With