n 以下的素数 - JavaScript
假设我们需要编写一个 JavaScript 函数,该函数采用一个数字(比如 n),并返回一个包含 n 以内的所有素数的数组。
例如,如果数字 n 为 24,则输出应为 −
const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];
示例
以下为代码 −
const num = 24;
const isPrime = num => {
let count = 2;
while(count < (num / 2)+1){
if(num % count !== 0){
count++;
continue;
};
return false;
};
return true;
};
const primeUpto = num => {
if(num < 2){
return [];
};
const res = [2];
for(let i = 3; i <= num; i++){
if(!isPrime(i)){
continue;
};
res.push(i);
};
return res;
};
console.log(primeUpto(num));输出
这将在控制台产生以下输出 −
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP