Richard
Richard

Reputation: 1

I have made a for-loop in Javascript to check if a number is a primenumber or not. But it's not working

I have made a for-loop in Javacript to check if a number is a primenumber or not. But it's not working. Who can help me with this?

Fill in a limit:<br>
<input type="number" id="limit" placeholder="limit" /></br>
<input type="submit" value="Go!" onclick="primenumbers()" /><br><br>
<p id="answer">Here comes the answer</p>

<script>
var answer = document.getElementById('answer');

function primenumbers() {
    var limit = document.getElementById('limit').value;

    answer.innerHTML = ' ';
    for(var i=0; i<=limit; i++) {
        if(i == 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113){
            answer.innerHTML += i+' = '+'Primenumber'+'<br>';
        } else {
            answer.innerHTML += i+' = '+'Not a primenumber'+'<br>';
        }
    }
}
</script>

Upvotes: 0

Views: 80

Answers (1)

Paul
Paul

Reputation: 141887

if(i == 2, 3, 5, ... , 113) is just a really long way of writing if (113), which is always true. That is how the comma operator works.

If you want to test if a value is included in a set of values you can use an array for the set, and search for that value in the set using Array.prototype.indexOf:

if ([2, 3, 5, ..., 113].indexOf(i) >= 0)

If you want that to work in Internet Explorer versions 8 or below you need to implement Array.prototype.indexOf in Javascript. There is a Polyfill here.

Upvotes: 2

Related Questions