Javascript生成器生成小于给定数的质数

时间:2019-07-16 13:07:50

标签: javascript

我需要以下代码的帮助

给定整数n使用javascript生成器生成所有小于n的素数

function *genPrime() {
    var count = 0;
    while(1) {
        if(getPrimes(count)) 
            yield count;
        return count++;
    }
}
function getPrimes(n) {
    if (isNaN(n) || !isFinite(n) || n%1 || n<2) 
        return false;
    var m = n;
    for (var i=0;i<=m;i++) 
        return true;
}

样本输入 10

样本输出 2 3 5 7

3 个答案:

答案 0 :(得分:0)

尝试一下:

function* genPrime(number) {
    var prime;
    var count = 0;
    while(count <= number) {
        if(getPrimes(count)) {
            yield prime = count;
        }
        count++;
    }
}
function getPrimes(n) {
    if (isNaN(n) || !isFinite(n) || n%1 || n<2) 
        return false;

    for(let factor = 2; factor < n; factor++){
        if(n % factor == 0){
            return false;
        }
    }

    // n is prime
    return true;
}
const iterator = genPrime(10)

console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);

答案 1 :(得分:0)

尝试以下代码:将所需的值传递给生成器,它将为您提供所有素数

function* genPrime(n) {

if (isNaN(n) || !isFinite(n) || n % 1 || n < 2)
    return " Number not valid : " + n;

    for (var i = 2; i < n; i++) {
        if (isPrime(i)) {
            yield i;
        }
    }
}


function isPrime(num) {
    for (var i = 2; i < num; i++) {
        if (num % i === 0) {
            return false;
        }
    }
    return true;
}
const generatorObject = genPrime(10);
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);
console.log(generatorObject.next().value);

答案 2 :(得分:0)

具有 O(√n̅) 来检查素数的复杂性:

let isPrime = (num) => {
    let isEven = num % 2 === 0
    if(num < 2 || (num > 2 && isEven)) return false;
    for(let i=3; i <= Math.sqrt(num); i += 2){
        if(num % i === 0) return false;
    }
    return true;
}
let getPrimes = function* (until = Infinity){
    for(let i=2; i < until; i++){
        if(isPrime(i)) yield i;
    }
}
console.log([...getPrimes(20)].join(', '))