हमें एक 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 ]