เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้ตัวเลขสองตัวที่ระบุช่วง ฟังก์ชันของเราควรส่งคืนจำนวนเฉพาะแบบสุ่มที่อยู่ในช่วงนั้น
ตัวอย่าง
รหัสสำหรับสิ่งนี้จะเป็น −
const range = [100, 1000];
const getPrimes = (min, max) => {
const result = Array(max + 1)
.fill(0)
.map((_, i) => i);
for (let i = 2; i <= Math.sqrt(max + 1); i++) {
for (let j = i ** 2; j < max + 1; j += i) delete result[j];
}
return Object.values(result.slice(min));
};
const getRandomNum = (min, max) => {
return Math.floor(Math.random() * (max − min + 1) + min);
};
const getRandomPrime = ([min, max]) => {
const primes = getPrimes(min, max);
return primes[getRandomNum(0, primes.length − 1)];
};
console.log(getRandomPrime(range)); ผลลัพธ์
และผลลัพธ์ในคอนโซลจะเป็น −
311
ผลลัพธ์มักจะแตกต่างกันไปในแต่ละรอบ