How to check if the value in a text box is prime or not with jQuery

前端 未结 1 1804
悲&欢浪女
悲&欢浪女 2020-12-18 16:52

I am trying to determine whether the value in a text box is prime or not using jQuery.

Here is what I\'ve tried so far, but it\'s not working:

1条回答
  •  温柔的废话
    2020-12-18 17:21

    Here is your code slightly modified

    DEMO http://jsfiddle.net/72FtQ/1/

    function isPrime(n) {
    
       // If n is less than 2 or not an integer then by definition cannot be prime.
       if (n < 2) {return false}
       if (n != Math.round(n)) {return false}
    
       // Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
       for (var i = 2; i <= Math.sqrt(n); i++) {
          if (n % i == 0) {return false}
       }
    
       // If n%i was never == 0 above, then n must be prime
       return true;
    
    }
    

    SOURCE http://studymaths.co.uk/topics/checkIfPrime.php

    0 讨论(0)
提交回复
热议问题