Can someone please give me guidance on getting the primenumbers here? This is homework so I don\'t want the answer but some pointers would be greatly appreciated. It\'s real
I considered the following in my implementation: Prime numbers are "natural numbers" and it is possible for negative values to be prime numbers. This is a more definitive solution with input sanitation:
function isPrime(num) {
//check if value is a natural numbers (integer)
//without this check, it returns true
if (isNaN(num) || num % 1 !== 0) {
return false;
}
num = Math.abs(num); //*negative values can be primes
if (num === 0 || num === 1) {
return false;
}
var maxFactorNum = Math.sqrt(num);
for (var i = 2; i <= maxFactorNum; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
//this method in action
for (var i = 1; i <= 40; i++) {
console.log(i + (isPrime(i) ? ", isPrime" : ""));
}
//checking anomalies
console.log(isPrime(1.22));
console.log(isPrime(1.44));
console.log(isPrime("string"));
I hope my answer proves to be more readable code that also uses best practices. For example, some answers leave the square root calculation in the loop causing the method to run that calculation on every loop.