Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การสร้างเลขเฉพาะสุ่มใน JavaScript

เราจำเป็นต้องเขียนฟังก์ชัน 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

ผลลัพธ์อาจแตกต่างในแต่ละครั้งที่รัน