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:
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.....
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With