Reputation: 655
This js program should display the first 100 prime numbers, but instead it crashes each and every time and I can't find the error! Could someone point me towards the best way to debug js code?! Thank you!
// initialisation of the array p holding the first 100 prime numbers
var p = [];
// set the first prime number to 2
p.push(2);
// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
var prime = true;
loop:
for (var item in p){
if (i%item === 0){
prime = false;
break loop;
}
}
if (prime)
p.push(i);
i = i + 2;
}
// display the first 100 prime numbers found
var i=1;
for (var item in p){
document.writeln(i,item);
i++;
}
Upvotes: -1
Views: 150
Reputation: 655
This is what the final working code looks like:
// initialisation of the array p holding the first 100 prime numbers
var p = [];
// set the first prime number to 2
p.push(2);
// find the first 100 prime numbers and place them in the array p
var i = 3;
var item;
var prime;
while (p.length < 100) {
prime = true;
for (item in p){
if (i%p[item] === 0){
prime = false;
break;
}
}
if (prime)
p.push(i);
i = i + 2;
}
// display the first 100 prime numbers found
var s = "";
for (item in p){
if (item != p.length - 1){
s = s + p[item] + ",";
}
else{
s = s + p[item];
}
}
alert(s);
Upvotes: 0
Reputation: 8949
Just change
if (i%item === 0){
to
if (i % p[item] == 0){
then it will work.
Upvotes: 1
Reputation: 574
First, put your algorithm in to a funciton and put this function into a page html. like:
<html>
<head>
<script>
function test(){
// initialisation of the array p holding the first 100 prime numbers
var p = [];
// set the first prime number to 2
p.push(2);
// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
var prime = true;
loop:
for (var item in p){
if (i%item === 0){
prime = false;
break loop;
}
}
if (prime)
p.push(i);
i = i + 2;
}
// display the first 100 prime numbers found
var i=1;
for (var item in p){
document.writeln(i,item);
i++;
}
}
</script>
</head>
<body>
<a onmouseclick="test()">test</a>
</body>
</html>
then open this page in Chrome or firefox.
press F12 to open the debug panel.
then go to Sources tag dans choose your page (for exemple: test.html) in the left view and make a stop point debug on the line var p =[];
then click the link test on the page to begin your debug. F10 to go to another line and F11 to enter method, F8 to go to next stop point.
Hope that helps.
Upvotes: 2
Reputation: 782158
Change:
for (var item in p) {
to:
for (var i = 0; i < p.length; i++) {
item = p[i];
for-in
iterates over the keys of an object or array, not the values.
Upvotes: 2