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:
- An outer loops that will start at 3, go to 20, increment by 1
- An inner loop that will start at 20, go to 0, and decrement by 1.
- 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.....