Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Prime number generator [duplicate]

I am trying to generate the first prime numbers that are less than 20 (the only way I know how to do it with my limited knowledge):

let arr = [];

for (let x = 3; x <= 20; x++) {
  for (let i = 20; i > 0; i--) {
    if (x % i !== i) {
      arr.push(x)
    }
  }
  console.log(arr)
}

I do want to preface by saying there is WAY more efficient methods out there, but I am trying to just do things by scratch and learn to be more efficient, rather than someone just tell me.

The intention of the code:

  1. An outer loops that will start at 3, go to 20, increment by 1
  2. An inner loop that will start at 20, go to 0, and decrement by 1.
  3. condition in the inner-loop: If the number x modulo the range of numbers i and it returns i, it is therefor not a prime.

Example:

7 is prime.

7 % 7 = 0
7 % 6 = 1
7 % 5 = 2
7 % 4 = 3
7 % 3 = 4
7 % 2 = 5
7 % 1 = 6

whereas

6 is not prime

6 % 6 = 0
6 % 5 = 1
6 % 4 = 2
6 % 3 = 3    <=== because of this
6 % 2 = 4
6 % 1 = 5

the output is 20 multiples of the the range of numbers from 3-20. i.e., 3,3,3,3,3,........20,20,20.....

like image 801
Raboush2 Avatar asked Nov 25 '25 03:11

Raboush2


1 Answers

Understanding the OP cares more about clarity than efficiency, there's one simple observation that reduces the search significantly and doesn't add much (really, any) complexity: a non-prime must have a prime divisor, so we can restrict the divisibility check to smaller primes that were already found.

Written simply...

let arr = [];

for (let x = 3; x <= 20; x++) {
  // check only the previously found primes
  let isPrime = true;
  for (let i = 0; i < arr.length; i++) {
    if (x % arr[i] === 0) {
      isPrime = false;
      break;
    }
  }
  if (isPrime) arr.push(x)
}

console.log(arr)

Written tersely...

let primes = [];

for (let x = 3; x <= 20; x++) {
  if (primes.every(prime => x % prime !== 0)) primes.push(x)
}

console.log(primes)
like image 54
danh Avatar answered Nov 27 '25 16:11

danh