Prime Numbers JavaScript

后端 未结 11 1155
长发绾君心
长发绾君心 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:40

    You should return a bool value and new function can be:

    function(n) {
        if(n === 1) { return false;}
        else if(n == 2) { return true;}
        else if(n == 3) { return true;}
        else { 
            for(i=Math.floor(Math.sqrt(n));i>=2;i--){
                //console.log(i);//maybe another var in here? 
                    if(n%i ==0 || n%2 ==0 || n%3 == 0) {return false;} 
            } 
            }
        return true;
    };
    

    In the OP, the control if(n%i !==0 && n%2 !==0 && n%3 !== 0) {return n;} was problematic because even if only single i satisfies this condition, the function returns the number as prime.

提交回复
热议问题