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