Home > Blockchain >  Javascript Prime number generator
Javascript Prime number generator

Time:12-31

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.....

CodePudding user response:

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)

CodePudding user response:

So there are a few flaws in the logic. There are a few ways to optimize the code and to fix the logic.

  • the outer loop can increment by 2 (evens aren't prime)
  • the inner loop doesn't need to start larger than x instead start x-1 and go to 1
  • add a flag (np not prime) to track if number isn't prime
    • if x % i is 0, then flag np and break (if some num (x) is divisible(mod ...===0) by smaller number(i) it isn't prime)
    • only add x if !np (or prime)
    • reset the flag for each x

let arr = [];
let np=false
for (let x = 3; x <= 20; x =2) {
  np=false
  for (let i = x-1; i > 1; i--) {
    if (x % i === 0) {
      np=true
      break
    }
  }
  if(!np){
    arr.push(x)
  }
}
console.log(arr)

  • Related