0

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>
Richard
  • 1
  • 2
  • For future reference, this may help you check for primality: http://stackoverflow.com/a/12287599/1387572. It uses a for loop! – geoff May 12 '14 at 07:36

1 Answers1

2

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.

Paul
  • 139,544
  • 27
  • 275
  • 264
  • i dont thinks so. The right part returns the last value 113. – DIDoS May 12 '14 at 07:40
  • @ele The comma operator evaluates its left expression and then its right expression and evaluates to the value of its right expression. For example: `var x = (5, 7, 50);` will assign 50 to `x` and then doing `var y = (x++, x++, 300)` will make `x == 52` and `y == 300`. – Paul May 12 '14 at 07:59
  • you are right. Pls add that he shouldnt "calculate" Prime numbers like that. I voted your answer up. – DIDoS May 12 '14 at 08:11
  • @ele I agree, that is not how primality testing is generally done, but I suspect that it suits his needs, as he must be aware that it breaks for primes `> 113`, and I think getting into the details of how to test for primes may be out of the scope of his question. – Paul May 12 '14 at 08:15
  • @YTowOnt9 I have tried a lot, but I don't understand how to use 'indexOf'. Can you help me a little bit? – Richard May 12 '14 at 09:19