Prime Numbers JavaScript

后端 未结 11 1151
长发绾君心
长发绾君心 2020-12-08 11:47

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

11条回答
  •  生来不讨喜
    2020-12-08 12:18

    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.

提交回复
热议问题