Created
May 12, 2015 19:43
-
-
Save federicobucchi/3636a2e90a57effd587b to your computer and use it in GitHub Desktop.
Count the number of prime numbers less than a non-negative number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var countPrimes = function(n) { | |
var counter = 0; | |
var input = n - 1; | |
var isPrime = function(input) { | |
var square; | |
if (isNaN(input) || !isFinite(input) || input % 1 || input < 2) { | |
return false; | |
} | |
square = Math.sqrt(input); | |
for (var i = 2; i <= square; i++) { | |
if (input % i === 0) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
while (input > 1) { | |
if (isPrime(input)) { | |
counter += 1; | |
} | |
input -= 1; | |
} | |
return counter; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment