猿问

JS 函数如何实现输入一个参数,输出比参数自身小的所有质数?

如题目所述。


四季花海
浏览 506回答 1
1回答

aluckdog

function primes(n) {&nbsp; var p = []&nbsp; var c = new Array(n).fill(false);&nbsp; for (var i = 2; i < n; ++i) {&nbsp; &nbsp; if (!c[i]) {&nbsp; &nbsp; &nbsp; p.push(i);&nbsp; &nbsp; &nbsp; for (var j = i + i; j < n; j += i) {&nbsp; &nbsp; &nbsp; &nbsp; c[j] = true;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp;&nbsp;&nbsp; return p;}console.log(primes(20)); // [2, 3, 5, 7, 11, 13, 17, 19]
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答