My attempt at generating the prime numbers less than 20 using my current knowledge is as follows:
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 acknowledge that there are more efficient methods available, but I prefer to start from scratch and improve my skills gradually rather than relying on shortcuts.
The purpose of the code is as follows:
- An outer loop starting from 3 to 20 with increments of 1.
- An inner loop starting from 20 to 0 with decrements of 1.
- The condition in the inner loop checks if the number x modulo i is not equal to i, indicating it is a prime number.
For 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 consists of multiples of numbers between 3-20 repeated 20 times. It does not accurately generate prime numbers as intended.