在数组Javascript中查找下一个质数

时间:2018-07-31 10:40:56

标签: javascript arrays primes

昨天我有一个采访问题,这一直困扰着我,试图弄清楚如何获得数组数字行中的下一个质数。

function isPrime(num) {
    for (var i = 2; i < Math.sqrt(num) + 1; ++i) {
        if (num % i === 0) {
            return false;
        }
    }

    return num !== 1;
}

function getNextPrime(prime) {
      for (var count = prime + 1; ; ++count) {
        if (isPrime(count)) {
            break;
        }
    }

    return count;
}



console.log(getNextPrime([1, 2, 3, 4, 5]));
console.log(getNextPrime([2, 7, 11, 13]));
console.log(getNextPrime([19, 2, 13, 4]));
console.log(getNextPrime([2, 4, 6, 8]));

2 个答案:

答案 0 :(得分:0)

//if prime next to last element of array?

    function isPrime(num) {
        for (var i = 2; i < Math.sqrt(num) + 1; ++i) {
            if (num % i === 0) {
                return false;
            }
        }
        return num !== 1;
    }

    function getNextPrime(prime) {
		var sortedArray = prime.sort((a,b)=> a-b);
	    var last = sortedArray[sortedArray.length-1];
        for (var count = last + 1; ; ++count) {
           if (isPrime(count)) {
               break;
           }
        }
        return count;
    }

    console.log(getNextPrime([1, 2, 3, 4, 5]));
    console.log(getNextPrime([2, 7, 11, 13]));
    console.log(getNextPrime([19, 2, 13, 4]));

答案 1 :(得分:0)

const isPrime = function(n){
		if (isNaN(n) || !isFinite(n) || n%1 || n<2) {
			return false;
		}

		if (n%2==0){
			return (n==2);
		}

		var sqrt = Math.sqrt(n);
		for (var i = 3; i < sqrt; i+=2) {
			if(n%i == 0){
				return false;
			}
		}

		return true;
	}

const getNextPrime = function* (){
		let nextNumber = 2;
		while(true){
			if(isPrime(nextNumber)){
				yield nextNumber;
			}
			++nextNumber;
		}
	}
  
  const nextNumner = getNextPrime();
  console.log(nextNumner.next().value);

每次调用nextNumner.next()。value时,我们都会获得下一个素数。