I'm a new web developer, been learning web dev for around 8-9 months. I recently became a mentor for new students in the bootcamp I graduated and I wanted to write a simple program to calculate all prime numbers up to a given upper limit. I have solved the exact same problem in C, C++ and Python. I am using the "naive" implementation, not the Sieve of Eratosthenes.
This is the code that works:
"use strict";
function primeNumbers() {
let highNumber;
highNumber = window.prompt("Calculate all prime numbers up to:");
for (let i = 2; i <= highNumber; i++) {
let numberOfDivisors = 0;
for (let j = 2; j < highNumber; j++) {
if (i % j == 0) numberOfDivisors += 1;
}
if (numberOfDivisors == 1) console.log(i);
}
}
Of course, j doesn't have to go all the way up to highNumber, as for any number, all possible divisors are less than half of the number. Thus, I changed the inside for loop making j only going up to Math.round(highNumber / 2 + 1):
"use strict";
function primeNumbers() {
let highNumber;
highNumber = window.prompt("Calculate all prime numbers up to:");
for (let i = 2; i <= highNumber; i++) {
let numberOfDivisors = 0;
for (let j = 2; j < Math.round(highNumber / 2 + 1); j++) {
if (i % j == 0) numberOfDivisors += 1;
}
if (numberOfDivisors == 1) console.log(i);
}
}
But this somehow breaks the code and causes unexpected results. I know all numbers are technically floating point numbers in JavaScript, but I thought that using Math.floor() would help me deal with that.
Any ideas on why this isn't working and what can be done? Thanks!