আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি সংখ্যা নেয়, বলুন n, প্রথম এবং একমাত্র যুক্তি হিসাবে।
তারপর ফাংশনটি 2 থেকে n সংখ্যা পর্যন্ত সমস্ত মৌলিক সংখ্যার গণনা ফেরত দেবে।
যেমন −
For n = 10, the output should be: 4 (2, 3, 5, 7) For n = 1, the output should be: 0
উদাহরণ
const countPrimesUpto = (num = 1) => {
if (num < 3) {
return 0;
};
let arr = new Array(num).fill(1);
for (let i = 2; i * i < num; i++) {
if (!arr[i]) {
continue;
};
for (let j = i * i; j < num; j += i) {
arr[j] = 0;
};
};
return arr.reduce( (a,b) => b + a) - 2; };
console.log(countPrimesUpto(35));
console.log(countPrimesUpto(6));
console.log(countPrimesUpto(10)); আউটপুট
এবং কনসোলে আউটপুট হবে −
11 3 4