हमें एक जावास्क्रिप्ट फ़ंक्शन लिखने की आवश्यकता है जो एक संख्या लेता है, 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 ]