math - Why does my JavaScript Prime Number-Generator not work? -
the aim of program list prime numbers 1 up. complete novice. began writing in c++ (unsuccessfully) , translated (js) aware of problems don't know how solve them: handling global variables, writing replaces, no timeout before writing, etc. important use external js file? in summary, how make work?
<!doctype html> <html> <head> <script> var number = 3; //to run through prime test var prime = [2]; //numbers found prime var found = 1; //counter primes found var runs = 0; //counter times number has been tested //numbers tested against smaller found primes function test() { window.scroll(0,document.height); //automatically view latest prime var line = document.createelement("div"); while(runs < found && (prime[runs] < (number / 2))) //has number passed tests { if(number % prime[runs] !== 0) //is number divisible smaller prime { runs = runs + 1; //number passed test } else //number not prime { number = number + 1; //next number generated runs = 0; //reset test counter next number settimeout(test, 100); //start running next number tests } } //number passed tests line.innerhtml = number; //prime number displayed document.body.appendchild(line); prime[found] = number; //prime number saved testing found = found + 1; //counter found increased number = number + 1; //next number generated runs = 0; //reset test counter next number settimeout(test, 100); //start running next number tests } </script> </head> <body> <form> <input type="button" onclick="test()"> </form> </body> </html>
on mathematical side,
var prime = [1];
1
isn't prime, , since 1
divides every number,
while (runs < found) //has number passed tests { if (number % prime[runs] !== 0) //is number divisible smaller prime { runs = runs + 1; //number passed test } else //number failed test { number = number + 1; //next number generated runs = 0; //reset test counter next number settimeout(test, 1000); //start running next number tests } } //number passed tests
always enters else
branch runs = 0
.
you can start var prime = [2];
or var prime = [];
, var found = 0;
.
Comments
Post a Comment