I have the next problem. I am trying to find all the prime numbers until the specified number as input but when I am inputting for example really big numbers such as 13480000 or 643513511, the algorithm somehow stops to iterate and my browser is getting too slow in terms of processing the function. Here is the html code:
<!DOCTYPE html>
<html lang="es">
<head>
<script src="esPrimo.js">
</script>
</head>
<body>
<h1>Lista de primos</h1>
<form name="formu">
<input id="txtValue" type="text" />
<input type="button" value="Calcular!" onclick="proceso()">
</form>
<p id="res">El resultado se escribe aqui</p>
</body>
</html>
Here is my javascript code for the file of esPrimo.js
function proceso() {
var value = document.querySelector('#txtValue').value;
var primos = getPrimos(value);
var output = document.querySelector('#res');
output.innerHTML = primos.toString();
}
function getPrimos (value) {
var primos = [];
for (var i = 1; i <= value; i++){
if (esPrimo(i)) primos.push(i);
}
return primos;
}
function esPrimo(n){
if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false;
var m = Math.sqrt(n);
for (var i = 2; i <= m; i++)
if (n % i == 0) return false;
return true;
}
On the last function where the program is getting the parameter, gets very slow. It checks if n is dividible by every integer 2, 3, 4, 5 ... up to sqrt(n) but this version has the fewest lines of code. Moreover, I tried another way of iterating through all prime numbers like:
function esPrimo(n) {
if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false;
if (n%2==0) return (n==2);
var m=Math.sqrt(n);
for (var i=3;i<=m;i+=2) {
if (n%i==0) return false;
}
return true;
}
Here it checks the divisor 2 separately: then, it proceeds to check odd divisors only, from 3 up to sqrt(n). At most half of the numbers between 3 and sqrt(n) are checked.
How could I be able to optimize the code so that my program is able to calculate faster this kind of iterations ?
Any suggestions or advice, it would be really appreciating and helpful cause I have been trying to find somehow of a solution this past week, but it was of no use. Furthermore, I have one last link of interest in which I delved into and helped me quite a lot I would say in terms of grasping the primality test of numbers.
Thanks