简体   繁体   中英

Prime Checker function in javascript is only returning one prime number from an array containing multiple prime numbers

Here is the code I'm using to go through an array and pick out the prime numbers and push them to an empty array. My problem is that when I node this, it's only returning the first prime number the code finds in the array regardless if there are more prime numbers in the array. I can't spot what I might be missing...

 let primeXray = function(num) {
    if (num < 2)
        return false;

    for (i = 2; i < num; i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}

let choosePrimes = function(nums) {
    let primeBlock = [];
    for (i = 0; i < nums.length; i++) {
        let num = nums[i];
        if (primeXray(num)) {
            primeBlock.push(num);
        }
    }
    return primeBlock;
}




console.log(choosePrimes([36, 48, 9, 13, 19])); // [ 13, 19 ]
console.log(choosePrimes([5, 6, 4, 11, 2017])); // [ 5, 11, 2017 ]

The problem is that you do not declare i with let or var , so it's created by JS and reused. Your primeXray changes i which disturbs the other function

let primeXray = function(num) {
    if (num < 2)
        return false;

    for (let i = 2; i < num; i++) {
        if (num % i === 0)
            return false;
    }
    return true;
}

let choosePrimes = function(nums) {
    let primeBlock = [];
    for (let i = 0; i < nums.length; i++) {
        let num = nums[i];
        if (primeXray(num))
            primeBlock.push(num);
    }
    return primeBlock;
}

Print the prime Numbers in 1-50; using loops in JavaScript

for (var counter = 0; counter <= 50; counter++) {

var notPrime = false;
for (let i = 2; i <= counter; i++) {
    if (counter%i===0 && i!==counter) {
        notPrime = true;
    }
}
if (notPrime === false) {
            console.log(counter);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM